Differences between Java and C ++: Polymorphism in Constructor

Source: Internet
Author: User

We have a class A that calls its own method F in the constructor.

Now there is a Class B that inherits a and overwrites method F.

Then, when constructor B calls the constructor A, does F in the constructor a refer to A: f or B: F?

In C ++, The polymorphism of function calls is mainly implemented through virtual tables. The virtual tables are not implemented before the constructor is completed, so there is no polymorphism at this time, therefore, the call is still a: f.

However, this is not the case in Java. It calls the subclass method, namely, B: f.

At this point, the C ++ performance should be more reasonable.

Therefore, in Java, if you guarantee that the method called is not a derived class method during the construction, you must call the private or final method. Because the final method will not be overwritten, and the private method is also. By default, the private method is actually final. overwriting the private method actually generates a new method.

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.