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

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

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

    Not necessarily!

    Now in your class B

    class B extends A {
    }
    

    you have not provided any constructor in Class B so a default constructor will be placed. Now it is a rule that each constructor must call one of it's super class constructor. In your case the default constructor in Class B will try to call default constructor in class A(it's parent) but as you don't have a default constructor in Class A(as you have explicitly provided a constructor with arguments in class A you will not have a default constructor in Class A ) you will get an error.

    What you could possibly do is

    Either provide no args constructor in Class A.

    A()
    {
      //no arg default constructor in Class A
    }
    

    OR

    Explicitly write no args constructor in B and call your super with some default int argument.

    B()
    {
        super(defaultIntValue);
    }
    

    Bottom line is that for an object to be created completely constructors of each parent in the inheritance hierarchy must be called. Which ones to call is really your design choice. But in case you don't explicitly provide any java will put default constructor super() call as 1st line of each of your sub class constructors and now if you don't have that in superclass then you will get an error.

提交回复
热议问题