Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you need to explicitly call a superclass constructor?

So say I have a subclass that extends a superclass. In what scenarios do I need to explicitly type super() to get the superclass constructor to run?

I'm looking at an example in a book about abstract classes and when they extend it with a non-abstract subclass, the subclass's default constructor is blank and there's a comment that says the superclass's default constructor will be called. At the same time I've also seen instances on here where someone's problem was not explicitly calling super().

Is the distinction from calling the superclass's default/non-default constructor from the subclass's default/non-default constructor?

like image 222
jhlu87 Avatar asked Jun 11 '11 21:06

jhlu87


People also ask

Do you have to call the superclass constructor?

It is required if the parameterized constructor (a constructor that takes arguments) of the superclass has to be called from the subclass constructor.

Why you would need to call the superclass constructor from its subclass?

This is required because the parent class must be initialized by one of its constructors, and if there isn't a default constructor, the java compiler has no way of knowing which constructor to call, or what parameters need to be passed.

What happen if the subclass constructor does not call a superclass constructor explicitly?

If a subclass constructor does not explicitly call a superclass constructor, Java will automatically call the superclass's default constructor, OR NO-ARG constructor, JUST BEFORE the code in the subclass's constructor executes.

Why call super must be first in constructor?

The Eclipse compiler says, Constructor call must be the first statement in a constructor . So, it is not stopping you from executing logic before the call to super() . It is just stopping you from executing logic that you can't fit into a single expression.


1 Answers

You never need just

super(); 

That's what will be there if you don't specify anything else. You only need to specify the constructor to call if:

  • You want to call a superclass constructor which has parameters
  • You want to chain to another constructor in the same class instead of the superclass constructor

You claim that:

At the same time I've also seen instances on here where someone's problem was not explicitly calling super().

Could you give any examples? I can't imagine how that's possible...

like image 160
Jon Skeet Avatar answered Oct 18 '22 01:10

Jon Skeet