Why does this class compile even though it does not properly implement its interface?

generics, java

Solution

The answer is in JLS 7 5.5.1. Reference Type Casting:

Given a compile-time reference type S (source) and a compile-time reference type T (target), a casting conversion exists from S to T if no compile-time errors occur due to the following rules.

If S is a class type:

If T is a class type, then either |S| <: |T|, or |T| <: |S|. Otherwise, a compile-time error occurs.

Furthermore, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types

(§4.5), and that the erasures of X and Y are the same, a compile-time error occurs.

In your case `List<Integer>` and `List<String>` are provably distinct parameterized types and they both have same erasures: `List`.

Problem

a List then Why does the code (below) compile? Surely `MyClass2` should return a `List<Integer>` ? ``` public class Main { public static void main(final String[] args) { MyClass myClass = new MyClass(); List list = myClass.getList(); System.out.println(list); System.out.println(list.get(0).getClass()); MyClass2 myClass2 = new MyClass2(); List list2 = myClass2.getList(); System.out.println(list2); System.out.println(list2.get(0).getClass()); } public interface Int1 { public List getList(); } public interface Int2 extends Int1 { @Override public List<Integer> getList(); } public static class MyClass implements Int2 { @Override public List<Integer> getList() { return Arrays.asList(1, 2, 3); } } public static class MyClass2 implements Int2 { @Override public List getList() { return Arrays.asList("One", "Two", "Three"); } } } ``` I have noticed if you try to make it a `List<String>` then you get an error "java: Main.MyClass2 is not abstract and does not override abstract method getList() in Main.Int2". I don't quite understand why you don't get this in the example above. Note: The solution to the problem in my project is to make the interface itself generic, i.e. `Int1<X>` (of course I use better names than this, its just an example).

Original source