Construct method call Super under inheritance condition

Source: Internet
Author: User

Run the Testinherits.java sample, observe the output, notice that the call relationship between the parent class and the subclass constructs a method to modify the code of the parents constructor method, explicitly call the other constructor of grandparent, notice whether the calling code is the first sentence, the impact is significant!

Program:

classGrandparent { Publicgrandparent () {System.out.println ("Grandparent Created."); }      Publicgrandparent (String string) {System.out.println ("Grandparent created.string:" +string); }}    classParentextendsgrandparent{ PublicParent () {//super ("hello.grandparent.");System.out.println ("Parent Created"); //super ("hello.grandparent.");        }}classChildextendsParent { PublicChild () {System.out.println ("Child Created"); }} Public classTestinherits { Public Static voidMain (String args[]) {child C=NewChild (); }}

Results:

1 Original Program

2 super in the first sentence

3 Super Not in the first sentence

Conclusion:

through Super called base class construction method , it must be sub-class construction methods in the first statement. Thinking Why do I have to call the construction method of the parent class before the constructor of the subclass is run? Can you turn around? Why can't it be reversed? because the initialization of a subclass causes the execution of the parent class constructor. The parent class inherits the grandparent class, and the child class inherits the parent class, because Super is in the parent class and calls its base class grandparent constructor, because super ("hello.grandparent.") With a parameter, the second constructor is called.

Construct method call Super under inheritance condition

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.