Code in Java
public class A {
int x;
public A() {
x = 0;
}
public void print() {
System.out.println("This is A");
}
}
public class B extends A {
int x;
public B() {
x = 1;
}
public void print() {
System.out.println("This is B");
}
}
B b = new B();
A a = b;
System.out.print(a.x);---------------->0
a.print();---------------->This is B
I am very confused. I create object b for B class, although I assign b to a, I think b should still point the class B. Why the "a.x" will return 0 instead of 1? Why a.x point to the x in A, but a.print() point to the print() method in B?
fields are not polymorphic but the methods are,
which means method will be invoked on the object which is referred by reference at runtime
field variables are tied to reference, so if you remove field x from class A and try the same code it will fail to compile
You are seeing some irregularities on how polymorphism is applied in Java. Polymorphism is seen where invoking a.print() invokes B's print(), while this is not the case for fields. The field is tied to the reference, so in this case b.x and a.x are distinct (although you could leave out x in B's definition and have a single field declared in the superclass. In that case, a form of hiding is seen.
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