Three prerequisites for Java polymorphism:
1. Inheritance
2. Subclasses overriding parent class methods
3. Parent class reference to child class object
And then look at an example
The output is:
It is concluded that when the three conditions of the Java polymorphism are full, it is found that the c.eat () call is actually eat of the subclass, but the c.age is called the age of the parent class, and C.play () is not compiled.
In the Java reference, however, father not only specifies how C accesses memory, but also the size of the memory space that can be accessed.
We see that the size of the father instance object is two rows, but the child instance object occupies three rows (here is a simple quantization).
So while C is pointing to the child instance object, but father it before, it can only access two rows of data, that is, C cannot access the age!!! in the child class. Can only access the age of the Father class, so output 40
We see that the method table of the parent takes three rows, and the child's method table is 4 rows, while C points to the instance object of the child class.
The object also has pointers to the method table of the child class, but since C is Father, C can only access the contents of the first 3 rows in the Child method table!!!
However, as stated earlier, in the process of forming a method table, the subclasses override the method to overwrite the original data in the table, that is, the third row of the method table of the child class is a reference to the Child.eat,
Instead of pointing to parent.eat (because the method table produces overrides), C accesses the child.eat. That is the method of the subclass!!! In this case, C is no way to directly access the Eat method of the parent class.
Java polymorphism from the JVM point of view