Inheritance is the deepest coupling between classes. When modifying the child or parent classes, you must be aware of the implications across this inheritance hierarchy.
For some problems, an alternative solution can be to break the polymorphic aspects of the class into a separate interface. This way, there is no requirement for the implementor to extend your class - they can just plug in another class that implements the polymorphic behaviour.
As mentioned, using the
final keyword can help by allowing the base class designer to specify which functions are designed to be overridden.
The problem was that the overwriting function was using objects in the the derived class before they had a chance to initialize. I used a null check to solve it. It was a simple fix, but I just thought it might be useful to know how to explicitly choose which version to use just in case a more complex situation arises.
[/quote]
Adding a null check sounds brittle, I wouldn't recommend it.
This is another solution:
public class Parent {
public Parent() {
doFoo();
}
private void doFoo() {
// parent logic...
}
public void foo() {
doFoo();
}
}
public class Child extends Parent {
@Override
public void foo() {
// child logic...
}
}