Procedure for generating subclasses
See Code:
class Person { String name; int Age ; Person () { System.out.print ("No parameter constructor for person"); } Person (String name,int. ) {this. name = name; this. Age = Age ; System.out.print ("The constructor of the person with 2 arguments") ; void eat () { System.out.print ("eat");} }
classStudentextendsperson{intgrade; Student () {//in the constructor of a subclass, you must call the constructor of the parent class//if the constructor of the parent class is not written, the compiler automatically adds super (); //super (call the corresponding constructor in the parent class according to the parameters);System.out.print ("parameterless constructor for student"); } Student (String name,intAgeintgrade) { //this.name = name; //this.age = age; Super(Name,age);//Reduce Duplicate Code This. grade =grade; }}
class text{ publicstaticvoid main (String args[]) { new Student ("Zhansan", 18,90); System.out.print (s.name); System.out.print (s.age); System.out.print (S.grade); }}
Methods to call the parent class constructor using super
Because subclasses inherit member variables and member functions of the parent class, but cannot inherit the constructor of the parent class, code duplication occurs when assigning a value to a member variable. To solve this problem, call the constructor of the parent class with super:
Note: Super is in the constructor in the first row.