Subclasses can explicitly invoke the constructor of the parent class through the Super keyword.
When the parent class does not provide a parameterless constructor, the constructor of the parent class must be explicitly called in the constructor of the subclass;
If the parent class provides a parameterless constructor, the constructor of the subclass can call the parent class's constructor without explicitly calling the parent class's parameterless constructor by default.
Package com.bjut.StudyTest;
Class Person {public Person
() {
System.out.println ("Base has no args.");
Public person (String temp) {
System.out.println ("Base:" + temp);
}
}
Class Student extends Person {public
Student () {
super ("a");
System.out.println ("Student has no args.");
}
Public Student (String temp) {
System.out.println ("Student:" + temp);
}
public class Testconstruction {public
static void Main (string[] args) {person
p = new Student ();//Call the constructor of the parent class first To display the invocation of the specified parent class constructor.
Student s = new Student ("B");//The constructor of the parent class is called first, and the parent class parameterless constructor is called by default.
}
}
Output:
Base:a
Student has no args.
Base has no args.
Student:b
When there is a parent class, the constructor of the parent class is executed before the object is instantiated, and then the constructor of the subclass is executed.
(Supplemental) The order in which the Java program initializes the execution of the work:
Parent class static variable-> parent class static code block-> subclass static variable-> subclass static code block
-> Parent class non-static variable-> static code block-> parent class constructor
-> Subclass Non-static code block-> subclass non-static variable-> sub-class constructor