This article mainly introduces the relevant information on the detailed explanation of constructor method calls under Java inheritance relationship. I hope this article can help everyone understand and master this part of the content. Friends in need can refer to it
Detailed explanation of the constructor call under Java inheritance relationship
When creating an object of a class in Java, if the class has a parent class, the constructor method of the parent class is called first, and then called Subclass constructor. If the parent class does not define a constructor, the default constructor without parameters automatically created by the compiler is called. If the parent class defines a public parameterless constructor, the parameterless constructor will be automatically called before calling the child class's constructor. If the parent class only has a parameterized constructor and no parameterless constructor, the subclass must explicitly call super (parameter list) in the constructor to specify a parameterized constructor. If the parent class defines a parameterless constructor, but the parameterless constructor is declared as private, the subclass must also explicitly call super (parameter list) in the constructor to specify a parameterized constructor. If the parent class has no other parameterized constructor, the subclass cannot be created.
There is a parent class | |||
---|---|---|---|
Private no-parameter constructor | Public no-parameter constructor |
|
|
None | None | All constructors will call the default constructor of the parent class | |
None | None | All constructors will call the defined parameterless constructor | |
None | Yes | All constructors must specify to call a constructor with parameters, or call some other constructor through this. | |
No | Yes | You can specify to call a certain constructor. If not specified, the no-argument constructor will be called. method. | |
Yes | None | Subclass cannot be constructed (parent class cannot derive subclass) | |
Yes | Yes | All constructors must specify to call a constructor with parameters, or call some other constructor through this construction method. |
class Parent { private String pString; Parent(){ pString = "p1"; } } class Child extends Parent { private String cString; Child() { cString = "c1"; } }
class Parent { private String pString; private Parent(){ pString = "p1"; } Parent(String s){ pString = "p2"; } } class Child extends Parent { private String cString; Child() { super(""); cString = "c1"; } }
The above is the detailed content of The constructor method under Java inheritance relationship calls the implementation method. For more information, please follow other related articles on the PHP Chinese website!