Suppose we have Sub
inherit compareTo
from Super
:
class Super implements Comparable<Super> {
@Override public int compareTo(Super o) {
return 0;
}
}
class Sub extends Super {}
And generic method max
that takes a list of Comparable
:
public static <T extends Comparable<T>> T max(List<T> list) {
return null;
}
If we try to call max
with the list of Sub
's we will get a compile-time error because Sub
doesn't implement Comparable<Sub>
. This is what I expected!
max(new ArrayList<Sub>()); // error, Sub should implement Comparable<Sub>
Then I change max
arguments to accept just two instances of T and test it:
public static <T extends Comparable<T>> T max(T t, T t2) {
return null;
}
max(new Sub(), new Sub());
No compile-time error, non runtime!
What is the difference between max
methods in terms of type safety?