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

后端 未结 12 1469
终归单人心
终归单人心 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:18

    Say this compiled, what would you expect it to print?

    class A{
      A(int i){
        System.out.println("A.i= "+i);
      }
    }
    
    class B extends A {
      public static void main(String... args) {
        new B();
      }
    }
    

    When A is constructed a value for i has to be passed, however the compiler doesn't know what it should be so you have specify it explicitly in a constructor (any constructor, it doesn't have to be a default one)

提交回复
热议问题