First look at the code
Class person {int age; string name; person () {system. out. println ("no-argument constructor for person");} person (INT age, string name) {This. age = age; this. name = Name; system. out. println ("parameter constructor of person");} void eat () {system. out. println ("dinner ");}}
Class student extends person {int grade; student () {// super (); system is added by default. out. println ("Student's no-parameter constructor");} student (INT age, string name, int grade) {// This. age = age; it is the same as the code in the parent class. // This. name = Name; Super (age, name); // call the constructor of the parent class this. grade = Grade ;}}
class Test{ public static void main(String args[]){ Student s2 = new Student(); Student s1 = new Student(18,"zhangsan",3); }}
In a subclass constructor, the constructor of the parent class must be called. If the constructor of the parent class is not explicitly called in the subclass constructor, the compiler automatically adds super (); call a specific parent class Constructor (similar to this) based on the parameters passed in the brackets ).
Why ??
The subclass inherits the member variables and member functions of the parent class, but cannot inherit the constructor. Repeated code is generated when assigning values to the member variables of the parent class in the constructor of the subclass. The super keyword is used to call the constructor of the parent class to solve this problem.
When super is used to call the constructor in the parent class, this line of code must be the first statement.
Subclass instantiation Process