patternjavaMinor
Empty method in abstract class
Viewed 0 times
abstractemptymethodclass
Problem
I have an abstract class which holds a hook method for a template method. Not all classes which extend this class will need to implement this method (in fact most will not, but a few will). As such I declared the method this way:
Should it instead be declared this way:
Which one would be considered better practice?
protected void applyExtraCriteria(Object extraCriteria) {
}Should it instead be declared this way:
protected abstract void applyExtraCriteria(Object extraCriteria);Which one would be considered better practice?
Solution
If you are really sure that an empty method body is okay for most sub-classes, you could follow the example of Swing listeners (e.g.
Update: Of course, if you can use Java 8, you can write default methods in interfaces, hence an abstract class isn't needed.
WindowListener / WindowAdapter): Make the methods in your Foo class abstract, but provide an abstract class called FooAdapter extending Foo, which implements that methods with empty bodies. That way you document your intentions: The methods must be implemented, but by extending the FooAdapter you say that you want for most of them the default implementation (which happens to have empty method bodies).Update: Of course, if you can use Java 8, you can write default methods in interfaces, hence an abstract class isn't needed.
Context
StackExchange Code Review Q#4362, answer score: 8
Revisions (0)
No revisions yet.