In Java, if a class does not have any constructors that are explicitly created, the class defaults to a parameterless constructor, and if you explicitly create a parameter constructor, the class no longer has a default parameterless constructor.
In Java inheritance, constructors are not inherited, but are displayed or implicitly called.
1. The constructor method of the subclass must be called in the constructor of its base class (display or implicit)
1.1, if the call is displayed, it can be called through Super (Argument_list), and the super call must be in the first row To ensure that the instance variables inherited from all direct or indirect parent classes are initialized correctly (the This keyword can call other constructors in this class, it must also be in the first sentence, so this and super cannot be used concurrently).
1.2. If no call is shown in the subclass construction method, the system implicitly calls by default-calls the parameterless construction method of the base class. Therefore, if there is no parameterless constructor in the base class at this time, an error will be compiled.
Example 1: Calling the parent class constructor is not shown in the subclass, the parent class parameterless constructor is called by default.
1 classFatherclass {2 3 PublicFatherclass () {4SYSTEM.OUT.PRINTLN (1);5 }6 7 PublicFatherclass (intAge ) {8 System.out.println (age);9 }Ten One } A - Public classSonclassextendsFatherclass { - the PublicSonclass () { - } - - PublicSonclass (intc) { +SYSTEM.OUT.PRINTLN (2); - } + A PublicSonclass (intAintb) { at Super(a); - System.out.println (b); - } - - Public Static voidMain (string[] args) { - NewSonclass (); in NewSonclass (10); - NewSonclass (10, 11); to } +}
Example 2: The subclass does not display the call to the parent class constructor and the parent class does not have a parameterless constructor, and the compilation error occurs.
1 classAA {2 PublicAA (inta) {3 ;4 }5 }6 7 classBbextendsAA {8 PublicBB () {//This constructor invokes the parent class constructor because it does not appear, so the parameterless constructor of the parent class is called implicitly. But the parent class does not have a parameterless constructor, so the compilation error: Implicit Super constructor AA () is undefined. Must explicitly invoke another constructor9SYSTEM.OUT.PRINTLN ("Test");Ten } One A PublicBB (inta) { - Super(a); - } the}
Order of execution of construction methods in Java inheritance