Subclass Generation Process
See the Code:
Class Person {String name; int age; Person () {System. out. print ("no-argument constructor of Person");} Person (String name, int age) {this. name = name; this. age = age; System. out. print ("constructor with two parameters for Person");} void eat () {System. out. print ("dinner ");}}
Class Student extends Person {int grade; Student () {// In the constructor of the subclass, the constructor of the parent class must be called. // If the constructor of the parent class is not written, then the compiler automatically adds super (); // super (calls the corresponding constructor in the parent class according to the parameter); System. out. print ("Student's no-parameter constructor");} Student (String name, int age, int grade) {// this. name = name; // this. age = age; super (name, age); // reduce repeated code this. grade = grade ;}}
class Text{ public static void main(String args[]){ Student s = new Student("zhansan",18,90); System.out.print(s.name); System.out.print(s.age); System.out.print(s.grade); }}
How to use super to call the parent class Constructor
Because the subclass inherits the member variables and member functions of the parent class, but cannot inherit the constructor of the parent class, the code will be repeated when assigning values to the member variables. To solve this problem, use super to call the constructor of the parent class ..
Note: super must be in the first line of the constructor.