Why default constructor is required(explicitly) in a parent class if it has an argumented constructor
class A { A(int i){ } } class B extends A { } class Main { public static void main(String a[]){ B b_obj = new B(); } }
This will be an error.
If a base class has a default constructor, i.e., a constructor with no arguments, then that constructor is automatically called when a derived class is instantiated if the derived class has its own default constructor.
What is the significance of the default constructor? They are used to create objects, which do not have any specific initial value. Is a default constructor automatically provided? If no constructors are explicitly declared in the class, a default constructor is provided automatically by the compiler.
A default constructor is a 0 argument constructor which contains a no-argument call to the super class constructor. To assign default values to the newly created objects is the main responsibility of default constructor.
What if I want the parent and child class to only have constructors with parameters? Am I right to conclude that a parent class always needs a default or no-arg constructor? No, it's fine to have a parent class without the default constructor as long as its children don't invoke super() .
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:
A
B
which explicitly calls the base class constructor with an appropriate int
argument.B
which calls the base class constructorWhy 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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With