When inheriting from a base class in a scenario when not all methods will be implemented, is it better to put empty methods in the base class so that sub-classes that don’t require that method can ignore it totally, while other classes must override the method if they want to implement it… e.g:
Base class:
public void myMethod() {
}
Sub-class that doesn’t implement:
<nothing!>
Or is it better to leave the base class cleaner and just put an abstract method in and force the sub-class to flesh out a blank method if it doesn’t implement that method?
Base class:
public abstract void myMethod();
Sub-class that doesn’t implement:
public void myMethod() {
}
It’s up to you and it really depends on the situation.
You can use abstract methods when you have an abstract class and you want classes which extend it to implement that method (because the abstract parent class uses the abstract method – it may be something like
print()). It’s similar to interface’s methods but it’s usually used in different scenarios. But I would use interface in most cases…I would use abstract method only in case that
myMethod()does a different thing in each class that extends the abstract parent… Otherwise, ifmyMethod()does usually the same thing and one or two classes need to override it, I will use the first solution.Also look at the template method pattern. I don’t know which case is yours so I can’t answer this question in an exact way…