I have to create a lot of very similar classes which have just one method different between them. So I figured creating abstract class would be a good way to achieve this. But the method I want to override (say, method foo()) has no default behavior. I don't want to keep any default implementation, forcing all extending classes to implement this method. How do I do this?
Asked
Active
Viewed 4.6k times
58
-
Sounds like an implementation of the Template Method Pattern http://en.wikipedia.org/wiki/Template_method_pattern – Robin Nov 17 '10 at 14:42
-
3This is an excellent question for cases where you want ALL subclasses to call their parent. The answers so far seem to have not considered that case. Example: ensure a method needs to overridden in every class and call the parent: `@override protected void importantMethod(){ super.importantMethod(); ... }` – will Sep 27 '16 at 01:46
-
I was looking for an answer to the comment that @will posted and found https://stackoverflow.com/questions/30046748/force-non-abstract-method-to-be-overridden – AvinashK Oct 05 '20 at 20:00
5 Answers
89
You need an abstract method on your base class:
public abstract class BaseClass {
public abstract void foo();
}
This way, you don't specify a default behavior and you force non-abstract classes inheriting from BaseClass
to specify an implementation for foo
.

Pablo Santa Cruz
- 176,835
- 32
- 241
- 292
-
11
-
3ah right! I was under the misconception that abstract classes canot have non-abstract methods. Thanks! – Hari Menon Nov 17 '10 at 11:51
11
Just define foo() as an abstract method in the base class:
public abstract class Bar {
abstract void foo();
}
See The Java™ Tutorials (Interfaces and Inheritance) for more information.

Jens Hoffmann
- 6,699
- 2
- 25
- 31
9
Just make the method abstract.
This will force all subclasses to implement it, even if it is implemented in a super class of the abstract class.
public abstract void foo();

Sean Patrick Floyd
- 292,901
- 67
- 465
- 588
5
If you have an abstract class, then make your method (let's say foo
abstract as well)
public abstract void foo();
Then all subclasses will have to override foo
.

Buhake Sindi
- 87,898
- 29
- 167
- 228