The examples in this article describe the constructor methods in Java inheritance. Share it with everyone for your reference. The details are as follows:
Constructor in inheritance:
1. During the construction process of a subclass, the construction method of its base class must be called.
2. Subclasses can use super(argument_list) in their own construction methods to call the construction method of the base class.
2.1. Use this(argument_list) to call other constructors 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 subclass does not explicitly call the constructor of the base class, the system calls the parameterless constructor of the base class by default.
4. If the subclass constructor does not explicitly call the base class constructor, and the base class does not have a parameterless constructor, a compilation error will occur.
The example code is as follows:
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 above syntax in turn.
I hope this article will be helpful to everyone’s Java programming design.