Why should the derived class constructor always ac

2019-07-03 16:28发布

问题:

I saw this question in one of my question papers:

Why should the derived class constructor always access base class constructor?

I'm wondering whether the question is valid?

回答1:

So that you may have a valid object of type "Base" before you start messing with the inherited functionality in your derived object!



回答2:

It's not valid. There's no 'should' about it: it must, and the compiler enforces it, by calling the base class's default constructor if it exists, and giving you a compile error if it doesn't, which forces you to call one of the existing constructors.



回答3:

There is one exception to always, a default constructor in a superclass isn't usually called explicit.

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.



回答4:

Because the base class may do work you are not aware of.



回答5:

Because the base class may have members that require initialization.



回答6:

Since the derived class constructor wants to inherits from the base class constructor, it is necessary to call the base class constructor. Otherwise, if you don't, you will not inherit values initialised in base class constructor.



回答7:

Calling a superclass constructor is not a must but a should paired with a strong advise - as long as the superclass has a default constructor. Otherwise the compiler forces you to call at least one of the superclasses constructors.

If the default constructor is present, it's called anyway, even without an explicit super() statement in the subclasses construtor.

A visible part of class construction is the initialization of fields. But there's more under the hood (memory allocation, registration, etc). All this has to be done for all superclasses when a derived class is created.