Inheritance constructor: inheritance Constructor

Source: Internet
Author: User

Inheritance constructor: inheritance Constructor

1 public class Test: Test2 // subclass 2 {3 public Test (): base () 4 {5} 6 7 public Test (int a): base () // pass the parameters of the subclass constructor to the constructor of the parent class 8 {9 //..... 10} 11 12} 13 14 public class Test2 // parent class 15 {16 public int a; 17 18 public Test2 () 19 {20} 21 22 public Test2 (int) 23 {24 //..... 25} 26}

The above code is the writing of the constructor of the subclass and parent class when we use inheritance. Whether constructor can be inherited should be understood as follows:

The parent class is the abstraction of child classes. That is to say, the parent class and child classes can be merged into a class. The constructor written by the merged class not only contains the constructor content of the Child classes, it also contains the constructor content of the parent class. Therefore, it is more reasonable for a subclass to call the constructor of the parent class. After inheritance, when the subclass is instantiated, it will first call the constructor of the parent class, and then call its own constructor, and we do not need to inherit from it, the constructor for merging and writing a class is similar. Therefore, subclass cannot inherit the constructor of the parent class.

 

Some special rules on constructor methods in inheritance:

The constructor of the Child class must call the constructor of the parent class and write the constructor of the Child class in the first line of the Child class constructor.

If the subclass constructor does not explicitly call the constructor of the parent class, the system calls the constructor without parameters in the parent class by default.

Related Article

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.