I just guessed that since the member variables of the parent class and the subclass are each stored in the heap, it may be because of the existence of the parent class, so the member variables of the parent class are found first. Then I tested it, the code is as follows:
package test;
public class Polymorphism {
public static void main(String[] args) {
F f = new Z();
f.show();
System.out.println("f:"+f);
System.out.println("f:"+f.a);
}
}
abstract class F{
int a = 10;
public abstract void show();
}
class Z extends F{
int a = 5;
public void show(){
System.out.println("Z:"+this);
System.out.println("Z:"+this.a);
}
}
The output is:
Z:test.Z@15db9742
Z:5
f:test.Z@15db9742
f:10
f and this point to the same object and access the same variable but have different results, so my guess above should be wrong. So what exactly causes polymorphic calls to member variables with the same name to access member variables of the parent class?
f refers to subclass objects. I have only heard of rewriting and overloading of methods, but not of class variables. The program I ran depends on the situation. If a method is called, it is the actual object pointed to (the actual object here is a subclass The method of object Z), if the class variable has the same name, is the class variable value of the living object.
Rewriting, overloading and dynamic linking of methods in Java constitute polymorphism. Polymorphism is different expressions of the same thing.
Your example is polymorphism demonstrated by method rewriting.
What is declared is the parent class F, which actually points to its subclass Z. This is equivalent to an upward type conversion, because Z is also inherited from F, so it can be upwardly converted. Now Z is of type F.
So here the f variable is instantiated by Z, but it is of type F and shows the characteristics of F.