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).