This discussion is archived
2 Replies Latest reply: Jul 6, 2010 5:56 AM by 843793 RSS

Tricky Generics problem covariant return types

843793 Newbie
Currently Being Moderated
Consider the following classes

class A {
}

class B extends A {
}

class C {
public <T extends A> T foo(Class<T> cls) {
System.out.println("A");
return null;
}
}
class D extends C {
public <T extends B> T foo(Class<T> cls) {
System.out.println("B");
return null;
}
public static void main(String[] args) {
D d = new D();
d.foo(B.class);
}
}

This will print "B" as one would expect. But if change main() to be like this:
C d = new D();
d.foo(B.class);

Then it will print "A". In other words, public <T extends B> T foo(Class<T> cls) does not override public <T extends A> T foo(Class<T> cls)

Rather dangerously apparently, the method that gets called doesn't depend on the object type but upon the variable type holding the reference. No dynamic binding.

Can anyone explain to me the logic of why <T extends B> shouldn't be a covariant subclass of <T extends A> and thus be overriding the superclass method?