I have a question about inheritance. I have the following code:
public class CovariantTest {
public A getObject(){
return new A();
}
public static void main(String[] args){
CovariantTest c1 = new SubCovariantTest();
System.out.println(c1.getObject().x);
}
}
class A {
int x =5;
}
class B extends A {
int x = 10;
}
class SubCovariantTest extends CovariantTest{
@Override
public B getObject(){
return new B();
}
}
Why when I call c1.getObject()
returns A
instead of returning B
? If I am instantiating c1
as SubCovariantTest
, should not call method getObject()
that returns new B()
?
When I create an instance of the parent class as a child class
CovariantTest c1 = new SubCovariant()
Should not look at the methods / attributes of the instantiated class new Subcovariant()
?