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