Constructor in java inheritance, and java inheritance Constructor
Constructor in inheritance
1. the constructor of the base class must be called during subclass construction.
2. Subclass can use super (argument_list) in its own constructor to call the constructor of the base class.
2.1 use this (argument_list) to call another constructor of this class.
2.2 If super is called, it must be written in the first line of the subclass constructor.
3. If the constructor of the base class is not displayed in the constructor of the subclass, the system calls the non-parameter constructor of the base class by default.
4. If the subclass constructor does not show that the base class constructor is called, and the base class does not have a constructor without parameters, a compilation error occurs.
class SuperClass{ private int n; //SuperClass(){ // System.out.println("SuperClass()"); //} SuperClass(int n){ System.out.println("SuperClass(int n)"); this.n = n; }}class SubClass extends SuperClass{ private int n; SubClass(){ super(300); System.out.println("SuperClass"); } SubClass(int n){ System.out.println("SubClass(int n):"+n); this.n = n; }}public class TestSuperSub{ public static void main (String args[]){ //SubClass sc = new SubClass(); SubClass sc2 = new SubClass(200); }}
Verify the preceding syntax in sequence.
Constructor in java inheritance
First, he looks for the parent class. The constructor is used to create an instance. In turn, you think that you inherit a parent class. If you do not use the constructor of the parent class, the parent class cannot be instantiated, who do you inherit? So like this idea, there is a sub-idea behind the father. if you manually call a parameter in the parent class, you need to instantiate the parent class once. if you do not manually call the constructor of the parent class, there will be an implicit super () above the implicit constructor of the subclass to instantiate the parent class and then instantiate the subclass,
Personal Understanding
Where is the difference between constructor and constructor in JAVA? Can constructor be inherited?
A constructor is a constructor. A constructor cannot be inherited and can be called using super.