Invoking non-final instance methods in constructors risks downcasting from a constructor to an overridden method as such:
public class Start {
public static void main(String[] args) {
try {
ClassB obj = new ClassB();
} catch(Exception e) { }
}
static class ClassA {
ClassA() { initSomething(); }
void initSomething() {
System.out.println("ClassA:: initSomething()...");
}
}
static class ClassB extends ClassA {
@Override
void initSomething() {
System.out.println("ClassB:: initSomething()...");
}
}
}
You now rely on every subclass to invoke super.initSomething()
.
In a lot of the constructors I've been looking at, overridable instance methods are invoked. Also, I've never seen a method marked final
.
Am I being stupidly pedantic by having a policy of not invoking non-final instance methods in constructors? In reality, such downcasting really is a corner case. What do experienced programmers do?