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

There are two aspects at work here:

  • If you do specify a constructor explicitly (as in A) the Java compiler will not create a parameterless constructor for you.

  • If you don't specify a constructor explicitly (as in B) the Java compiler will create a parameterless constructor for you like this:

    B()
    {
        super();
    }
    

(The accessibility depends on the accessibility of the class itself.)

That's trying to call the superclass parameterless constructor - so it has to exist. You have three options:

  • Provide a parameterless constructor explicitly in A
  • Provide a parameterless constructor explicitly in B which explicitly calls the base class constructor with an appropriate int argument.
  • Provide a parameterized constructor in B which calls the base class constructor

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().


Every subclass constructor calls the default constructor of the super class, if the subclass constructor does not explicitly call some other constructor of the super class. So, if your subclass constructor explicitly calls a super class constructor that you provided (with arguments), then there is no need of no arguments constructor in the super class. So, the following will compile:

class B extends A{
     B(int m){
        super(m);
     }
}

But the following will not compile, unless you explicitly provide no args constructor in the super class:

class B extends A{
     int i; 
     B(int m){
        i=m;
     }
}

Tags:

Java