Source: http://www.cnblogs.com/sunnychuh/archive/2011/09/09/2172131.html
---------------------
Java inheritance does not inherit from constructors, just calls (implicit or explicit).
Here is an example:
public class Fatherclass {
Public Fatherclass () {
SYSTEM.OUT.PRINTLN (100);
}
Public Fatherclass (int.) {
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 is the result of post-compilation execution?
Analysis: sonclass s = new Sonclass (66); When executing this sentence, call the
Public sonclass (int c) {
SYSTEM.OUT.PRINTLN (1234);//The Non-parametric constructor (super ()) of the parent class is called automatically first
}
In this constructor, it is equivalent to the
Public sonclass (int c) {
Super ();//Must be line 1th, otherwise it cannot be compiled
SYSTEM.OUT.PRINTLN (1234);
}
So the result is 100.
1234
When you create an object of a subclass, 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 from the topmost parent of the inheritance tree, which guarantees that the instance variables inherited from all direct or indirect parent classes are correctly initialized by the child class object.
3. If the subclass constructor is written like this
public sonclass (int c) {
Super (22);//Must be line 1th, otherwise it cannot be compiled
//When super is called explicitly, the system no longer calls the no-argument super ();
SYSTEM.OUT.PRINTLN (1234);
}
The execution result is 22.
1234
Summary 1: Constructors cannot inherit, just invoke.
If the parent class has no parameterless constructors
When you create a subclass, you cannot compile unless the first row in the constructor code body must be the first row to explicitly call the parent class with the parameter constructor
As follows:
Sonclass () {
Super (777);//Show Call parent class with parameter constructor
SYSTEM.OUT.PRINTLN (66);
}
If you do not see the call to the parent class with the parameter constructor, the default call to the parent class without the parameter constructor super ();
But there is no parameterless constructor in the parent class, and it is not a call. So the compilation will not pass.
Summary 2: Once the parameter constructor is created, the system no longer has a default parameterless constructor.
If there are no constructors, the system will default to one without a parameter constructor.
Whether the Java subclass inherits the constructor when inheriting the parent class