Re: Rationale behind constructor call chain... ( and comparison with
C++)
A.B. wrote:
Just a question...
If an object B extends an object A, whenever B is constructed, A is
constructed... if A() calls a
function that is overloaded in B, it looks like the overloaded function
is called by the A constructor ...
I think you mean class B and class A. If B extends A, then an instance
of B is itself an instance of A.
( In C++ the behavior is always to call the function defined in A when
called within the A constructor, even if the overloaded function is B
is virtual. )
And abort(?) if the method is abstract.
Can someone explain me the rationale behind java's behavior in that
case, how it's useful, more logical etc than the C++ approach... can
this behavior be overriden?
The idea of overriding is that the base classes method is overridden
always. It does cause problems in that you can have a method called
which tries to use fields that have not been initialised yet, but it's
better to fail obviously in development than do something subtly wrong
through to production.
This means that factory methods work from the constructor. For instance
you'll often see in Swing components have protected create methods that
are called from the constructor.
If you really wanted to, you could add an "initialised" boolean
variable. Set it after the super constructor is called. In you
overriding methods, if it has not been set just call the super method
and exit. I'd be interested to see any uses of this, as in nine years of
Java programming I have not come across one.
Tom Hawtin