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

后端 未结 12 1465
终归单人心
终归单人心 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 22:00

    Assuming that you meant to write class B extends A:

    Every constructor has to call a superclass constructor; if it does not the parameterless superclass constructor is called implicitly.

    If (and only if) a class declares no constructor, the Java compiler gives it a default constructor which takes no parameters and calls the parameterless constructor of the superclass. In your example, A declares a constructor and therefor does not have such a default constructor. Class B does not declare a constructor, but cannot get a default constructor because its superclass does not have a parameterless constructor to call. Since a class must always have a constructor, this is a compiler error.

提交回复
热议问题