Why default constructor is required in a parent class if it has an argument-ed constructor?

后端 未结 12 1530
终归单人心
终归单人心 2020-11-29 21:17

Why default constructor is required(explicitly) in a parent class if it has an argumented constructor

class A {    
  A(int i){    
  }
}

class B extends          


        
12条回答
  •  鱼传尺愫
    2020-11-29 21:53

    When extending a class, the default superclass constructor is automatically added.

    public class SuperClass {
    }
    
    public class SubClass extends SuperClass {
       public SubClass(String s, Product... someProducts) {
          //super(); <-- Java automatically adds the default super constructor
       }
    }
    

    If you've overloaded your super class constructor, however, this takes the place of the default and invoking super() will thus cause a compile error as it is no longer available. You must then explicitly add in the overloaded constructor or create a no-parameter constructor. See below for examples:

    public class SuperClass {
       public SuperClass(String s, int x) {
         // some code
       }
    }
    
    public class SubClass extends SuperClass {
       public SubClass(String s, Product... someProducts) {
          super("some string", 1);
       }
    }
    

    OR...

    public class SuperClass {
       public SuperClass() {
         // can be left empty.
       }
    }
    
    public class SubClass extends SuperClass {
       public SubClass(String s, Product... someProducts) {
          //super(); <-- Java automatically adds the no-parameter super constructor
       }
    }
    

提交回复
热议问题