Constructor instance resolution in Java inheritance

  • 2020-04-01 03:30:22
  • OfStack

This article illustrates a constructor in Java inheritance. Share with you for your reference. The details are as follows:

Constructor in inheritance:

1. During the construction of a subclass, the constructor of its base class must be called.

2. A subclass can use super(argument_list) in its 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 on the first line of the subclass constructor.

3. If there is no constructor shown in the constructor of the subclass to call the constructor of the base class, the system will call the no-parameter constructor of the base class by default.

4. If the subclass constructor is not shown to invoke the base class constructor, and the base class has no parameterless constructor, the compilation fails.

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 has been helpful to your Java programming


Related articles: