5
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 the method getObject()
returning new B()
?
When I create an instance of the Father class as a Son class
CovariantTest c1 = new SubCovariant()
You should not look at the methods/attributes of the instantiated class new Subcovariant()
?
+1, perfect, I only published mine because I was already halfway through and I think I explained it in a slightly different way :)
– Math
Perfect and clear explanation. It is even difficult to accept only one.
– placplacboom