Override the list result type in Java
I want to compile some variations of this code in Java
class X { List<X> getvalue(){...}; } class Y extends X { List<Y> getvalue(){...}; }
Javac (1.6) returned an error because list < Y > and list < x > are incompatible
The key is that I want the compiler to recognize that list < Y > is a compatible return input list < x > if y is a subtype of X The reason I want is to simplify the use of user - defined factory classes
Note: this question is a bit like this question, but for Java
Solution
In Java, the return type of the overridden method must be covariant with the return type of the overridden method
Class java util. List is not covariant (in fact, there is no Java class. This is due to the lack of declaration - site variance annotation) In other words, B <: A does not mean list < b > List < a > (read & lt;: as subtype of) Therefore, your code will not be type checked
In Java, you have a definition - site differences Therefore, the following are typechecks:
import java.util.List; class X { List<? extends X> getvalue() { return null; } } class Y extends X { List<Y> getvalue() { return null; } }