A constructor in the base class can reference uninitialized fields or potentially cause other damage while calling an overridable method. This is because, it is possible for the wrong version (in a sub class) of the method to get invoked.
Non-Compliant Code Example
This non-compliant example invokes the doLogic
method from the constructor. The super class method is invoked on the first call, however, the overriding method is invoked on the second one. The issue is that the constructor for SubClass
is not invoked which leaves the value of color
as null
.
class BaseClass { public BaseClass() { doLogic(); } public void doLogic() { System.out.println("This is super-class!"); } } class SubClass extends BaseClass { private String color = null; public SubClass() { super(); color = "Red"; } public void doLogic() { System.out.println("This is sub-class! The color is :" + color); //color becomes null //other operations } } public class Overridable { public static void main(String[] args) { BaseClass bc = new BaseClass(); //prints "This is super-class!" BaseClass sc = new SubClass(); //prints "This is sub-class! The color is :null" } }
Compliant Solution
This compliant solution declares the doLogic
method as final
so that it is no longer overridable.
class BaseClass { public BaseClass() { doLogic(); } public final void doLogic() { System.out.println("This is super-class!"); } }
References
JLS, Chapter 8