public class CovariantTest {
public A getObj() {
return new A();
}
public static void main(String[] args) {
CovariantTest c = new SubCovariantTest();
System.out.println(c.getObj().x);
}
}
class SubCovariantTest extends CovariantTest {
public B getObj() {
return new B();
}
}
class A {
int x = 5;
}
class B extends A {
int x = 6;
}
The above code prints 5 when compiled and run. It uses the covariant return for the over-ridden method.
Why does it prints 5 instead of 6, as it executes the over ridden method getObj in class SubCovariantTest.
Can some one throw some light on this. Thanks.
Covariant return type refers to return type of an overriding method. It allows to narrow down return type of an overridden method without any need to cast the type or check the return type. Covariant return type works only for non-primitive return types.
How is Covariant return types implemented? Java doesn't allow the return type-based overloading, but JVM always allows return type-based overloading. JVM uses the full signature of a method for lookup/resolution. Full signature means it includes return type in addition to argument types.
More specifically, covariant (wide to narrower) or contravariant (narrow to wider) return type refers to a situation where the return type of the overriding method is changed to a type related to (but different from) the return type of the original overridden method.
Java version 5.0 onwards it is possible to have different return types for an overriding method in the child class, but the child's return type should be a subtype of the parent's return type. The overriding method becomes variant with respect to return type.
This is because in Java member variables don't override, they shadow (unlike methods). Both A and B have a variable x. Since c is declared to be of type CovarientTest, the return of getObj() is implicitly an A, not B, so you get A's x, not B's x.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With