R
Robert Klemme
Because getClass() is final, it didn't occur to me, that he
would have put up *that* as an example...
Now there we have something *I* have overlooked.
picked it because getClass() always returns the actual class of the
instance regardless from which constructor it is invoked (other than
in C++) - but yes, it's probably not the perfect example.
As for me, I can't remember having shot myself in the foot with this
feature of Java (i.e. allowing to invoke virtual methods in
constructor). I reckon, language designers figured that allowing it
is more worthwhile than preventing it. As Thomas pointed out you
would have to provide constructor arguments so subclasses can pass on
data they have created. This is tiresome and may even end up being
inefficient namely in the case where the superclass constructor needs
to decide which methods to call (or whether methods to call). You
would end up creating objects which then need to be discarded if the
super class constructor decides that he does not need them =>
inefficient code.
The example of that Library class-hierarchy looked a bit
contrived to me.
Btw, the check would be expensive for the compiler and I am also not
sure how that byte code might look like because you need to extend the
restrictions to all methods. [...]
It would be already an improvement, if direct calls to such
methods from the constructor were forbidden.
I am not convinced. The risk seems rather low compared to the efforts
needed to implement your rule and the fact that now suddenly we get an
inconsistency: direct calls are forbidden while indirect calls are
allowed. Everybody needing this would instantaneously would start
swearing and a second later introduce a private method whose only
purpose is to delegate the call to the "forbidden" method. No, I
don't think this is a good idea. After all we are grown ups and
should take responsibility for the code we write. How often did you
shoot yourself in the foot because you are allowed to invoke sub class
methods from a constructor?
Cheers
robert