...
This noncompliant example invokes the doLogic
method from the constructor. The super class doLogic
method is gets invoked on the first call, however, the overriding method is invoked on the second one. The In the second call, the issue is that the constructor for SubClass
is not invoked which leaves the initiates the super class's constructor which undesirably ends up calling SubClass
's doLogic()
method. The value of color
is left as null
because the initialization of the BaseClass
has not yet concluded.
Code Block | ||
---|---|---|
| ||
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" } } |
...