A
Andreas Leitgeb
There is well-known danger in calling own methods from the
constructor, namely that the method called may be overridden
by a subclass, which is really instanciated, but whose specific
constructor has not yet been run.
I do not intend to delve into the details of static, private
or final methods, or final'ity of the class itself (and maybe
others) avoiding these problems, but instead I'm curious, why
Java just doesn't simply forbid the dangerous calls.
Is there any *good* use of having the constructor call a method
that actually *can* be overridden in a subclass? I mean, are
there (non-anti)patterns of explicitly allowing subclasses to
hook into base-class's construction?
--- sscce Test.java begin ---
public class Test {
Test() { foo(); }
void foo() { }
}
--- sscce Test.java end ---
PS: I know that this is not the only spot where Java does let one
shoot in one's feet. But unlike other situations, this one just
seems so easy to detect from static analysis.
constructor, namely that the method called may be overridden
by a subclass, which is really instanciated, but whose specific
constructor has not yet been run.
I do not intend to delve into the details of static, private
or final methods, or final'ity of the class itself (and maybe
others) avoiding these problems, but instead I'm curious, why
Java just doesn't simply forbid the dangerous calls.
Is there any *good* use of having the constructor call a method
that actually *can* be overridden in a subclass? I mean, are
there (non-anti)patterns of explicitly allowing subclasses to
hook into base-class's construction?
--- sscce Test.java begin ---
public class Test {
Test() { foo(); }
void foo() { }
}
--- sscce Test.java end ---
PS: I know that this is not the only spot where Java does let one
shoot in one's feet. But unlike other situations, this one just
seems so easy to detect from static analysis.