58

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?

demongolem
  • 9,148
  • 36
  • 86
  • 104
Hari Menon
  • 31,521
  • 13
  • 78
  • 107
  • Sounds like an implementation of the Template Method Pattern http://en.wikipedia.org/wiki/Template_method_pattern – Robin Nov 17 '10 at 14:42
  • 3
    This 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 Answers5

88

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
  • 170,119
  • 31
  • 233
  • 283
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,589
  • 2
  • 22
  • 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
  • 284,665
  • 62
  • 456
  • 576
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
  • 85,564
  • 27
  • 164
  • 223
4

Make this method abstract.

vitaut
  • 43,200
  • 23
  • 168
  • 291