super man! Always be the first statements.
Hi guys,
why must super( ) always be the first statement executed inside a subclass' constructor?
Is it because in a multiple class hierachy, the order in which constructors are executed is as the derivation order? (i.e. Class -> Subclass -> SubSubclass -> ...)
Thanks
Reza
There's nothing to force you to call the super class' constructor inside a subclass' one. But when you want to call super class' constructor, it must be the first statement. Because it simply does not make sense not to do so.
Constructors are executed when they are called. Just like other methods. When you create a new instance of an object, you are indeed calling its constructor.
> It's not necessary.
Wrong
You can even omit super() call.
Yes. But if you do, it will add a super() call for you.
> There's nothing to force you call the super class'
> constructor inside a subclass' one.
Actually, you [must call a superclass constructor within a subclass constructor, and you must call it as the first statement in the constructor
> Constructors are executed when they are called. Just
Basically, you are right. I just want to point out that calling new x() implicitly calls the constructor, it is not explicitly invoked (you can call another constructor from within a constructor though)
> why must super( ) always be the first statement
> executed inside a subclass' constructor?
There are good technical reasons for this, the best possibly being that it would make possible to subclass any non-final class and change its functionality completely, but philosophically, it is because you are extending an existing class, therefore the original functionality should still be set up.
Yes, I meant it's not necessary to manually call it.
Let me express further. I think the idea is the constructor of a class should function exactly like it's superclass' constructor, only initializing additional things that are specific to the subclass. Calling super() after some statements in a subclass' constructor can interfere with superclass' one.
> Hi guys,
>
> why must super( ) always be the first statement
> executed inside a subclass' constructor?
Because we want the parent class to be completely constructed and in a valid state before we start doing anything with the child class (which may depend on the parent being in a valid state).
jverda at 2007-7-12 20:37:42 >
