If I create an object of a sub-class with no constructors, then I know that the compiler will implicitly provide a default constructor. What if I create a constructor in the sub-class and try to access the super class constructor using the super keyword, and, now, the super class has no constructor in it. Will the compiler provide a default constructor for the super class as well?
Relating Constructor of Super Class in java
71 views Asked by Frosted Cupcake AtThere are 6 answers
Does the compiler provides a default constructor for the super class also???
The default constructor will be there whether or not there is a subclass that needs it. The default is supplied when the parent is compiled, not later.
...What if I created sub class Constructor and trying to access the super class constructor using the super keyword,and the super class has no constructor in it.
But it does: The default one.
It goes like this.
Lets speak about Object which is the supermost class in java, If you open an editor and just make a class, then it is presumed that It is extending Object. Every class in Java extends from Object. If you do not write your own constructor then Compiler will provide one.
But if you write your own constructor let's say a constructor with one argument, compiler will not provide you with any constructor.
Now lets say taht you extend the above class, then compiler will complain you saying that the superclass does not have a default constructor rather a custom constructor so you need to make one constructor for this child class since first constructor which is called starts from the supermost class that is OBJECT and then proceeds down the line.
Hope this answers comprehensively, Thanks.
If the super class doesn't have explicit constructor, then an implicit default constructor will be added to it. So your super()
will invoke that.
If the super class only have some constructors with parameters. Then super()
in the sub-class won't compile. You have to explicitly use one of the defined super-class constructor super(param1, param2, ...)
, since super()
will be called if you don't call it.
Yes, if there is no specified constructor, there is always default empty constructor