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

后端 未结 12 1538
终归单人心
终归单人心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 21:56

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

    I would say this statement is not always correct. As ideally its not required.

    The Rule is : If you are explicitly providing an argument-ed constructer, then the default constructor (non-argumented) is not available to the class.

    For Example :   
    class A {    
      A(int i){    
      }
    }
    
    class B extends A {
    }
    

    So when you write

    B obj_b = new B();
    

    It actually calls the implicit constructor provided by java to B, which again calls the super(), which should be ideally A(). But since you have provided argument-ed constructor to A, the default constructor i:e A() is not available to B().

    That's the reason you need A() to be specifically declared for B() to call super().

提交回复
热议问题