In Java inheritance, constructor is not inherited, but called (implicitly or explicitly ).
The following is an example:
Public class fatherclass {
Public fatherclass (){
System. Out. println (100 );
}
Public fatherclass (INT age ){
System. Out. println (AGE );
}
}
Public class sonclass extends fatherclass {
Public sonclass (){
}
Public sonclass (INT c ){
System. Out. println (1234 );
}
Public static void main (string [] ARGs ){
Sonclass S = new sonclass (66 );
}
}
What are the execution results after compilation?
Analysis:Sonclass S = new sonclass (66); called when this sentence is executed
Public sonclass (INT c ){
System. Out. println (1234); // the system automatically calls the no-argument Constructor (Super () of the parent class first ())
}
In this constructor, it is equivalent
Public sonclass (INT c ){
Super (); // It must be 1st rows; otherwise, it cannot be compiled.
System. Out. println (1234 );
}
So the result is 100.
1234
When creating a subclass object, the Java Virtual Machine first executes the constructor of the parent class, and then executes the constructor of the subclass. In the case of multi-level inheritance, the constructor of each class is executed in sequence starting from the parent class at the top of the inheritance tree, this ensures that the subclass object is correctly initialized from all instance variables inherited directly or indirectly from the parent class.
3. If the subclass constructor is written in this way
Public sonclass (INT c ){
Super (22); // It must be 1st rows; otherwise, it cannot be compiled.
// After explicitly calling super, the system will no longer call Super () without parameters;
System. Out. println (1234 );
}
The execution result is 22.
1234
Conclusion 1: constructor cannot be inherited, but only called.
If the parent class does not have a constructor
The subclass cannot be compiled unless the constructorCodeThe first line of the object must be the first line that explicitly calls the constructors with parameters of the parent class.
As follows:
Sonclass (){
Super (777); // displays the constructors that call the parent class with Parameters
System. Out. println (66 );
}
If the parameter constructor of the parent class is not displayed, the system calls the super () function of the parent class without parameters by default ();
But the parent class does not have a constructor without parameters, so it cannot be called. Therefore, compilation fails.
Conclusion 2: After a constructor with parameters is created, the system will no longer have default constructor.
If there is no constructor, the system will have a non-argument constructor by default.