When I see the Java Inheritance section today, I have some problems with the constructor's inheritance and how to use it, and then find the relevant data to solve it.
Here is my personal summary:
First, create a parent class with two constructors:
Public class Jisuan { protectedint a=4; // constructor 1 Jisuan () { System.out.println ("no parameter constructor for parent class"); } // Constructor 2 Jisuan (int a) { System.out.println ("parameter constructor for parent class");} }
Create another subclass with two constructors:
Public class extends Jisuan { // Constructor 3public jisuankid () { System.out.println ( "parameterless constructor for subclasses"); } // Constructor 4 Public Jisuankid (int a) { System.out.println ("parameter constructor for the subclass");} }
Then create a third class;
Public class Testarray { publicstaticvoid main (string[] args) { new Jisuankid (3);}
}
1. Execution at this time:
Results:
Parameterless constructor for parent class
Parameter constructors for subclasses
2. Remove the constructor function 1
Result: Error
3. Remove the constructors 1 and 2
Execution Result:
Parameter constructors for subclasses
4. Remove the constructor function 4
Execution Result:
Parameterless constructor for parent class
Error occurred
The conclusions are as follows :
1. Subclasses cannot inherit the constructor of a parent class
2. If there are no constructors in the parent class, the system defaults to the parameterless constructor, and the child class object is created by calling the default parameterless constructor of the parent class to create the parent class. The corresponding constructor of the subclass is then called
3. If there is a parameter constructor in the parent class, the system does not add a default parameterless constructor, and when the subclass object is created, the parent class's parameterless constructor is called to create the parent class object, because the parent class does not have a parameterless constructor at this time, it will error.
4. In addition, you can use Super () or super (parameter name) in the constructor of the subclass to use the parameterless constructor and the parametric constructor of the parent class.
Problems with constructors when Java inherits