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.