Relating Constructor of Super Class in java

81 views Asked by At

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?

6

There are 6 answers

0
ppysz On

Yes, if there is no specified constructor, there is always default empty constructor

0
T.J. Crowder On

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.

0
Abhijeet On

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.

0
Luiz Junior On

Yes the super always occurs even if you didnt explicit declare

   public class FatherTest {

   }


public class SonTest extends FatherTest{

public SonTest(String sonName){
    super(); // this will always occurs

    }

}
0
user253751 On

If you don't write a constructor for a class, the compiler will implicitly add an empty one for you.

That means this:

public class X {
}

is identical to this:

public class X {
    public X() {
        // there's also an implicit super(); added here, but that's not directly relevant
    }
}
0
Morrissss On

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.