public class CovariantTest {
public A getObj() {
return new A();
}
public static void main(String[] args) {
CovariantTest c = new SubCov
I was looking at your code and was having some trouble compiling it. Getting error
The return type is incompatible with CovariantTest.getObj()
I made a small change.
class A {
int x = 5;
}
class B extends A {
int x = 6;
}
public class CovariantTest {
public A getObj() {
return new A();
}
public static void main(String[] args) {
CovariantTest c = new SubCovariantTest();
A a = c.getObj();
System.out.println(c.getObj().x);
}
}
class SubCovariantTest extends CovariantTest {
public A getObj() {
return new B();
}
}
Stick a breakpoint in at the system out line and look at the a variable. It contains two x members, with one set to 5 and one to 6.
Starblue's answer explains this behaviour.