Java polymorphism from the JVM point of view

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.