13

How can I write a method and force the subclasses to override this method. In Eclipse it should show in the Quick-Fix Dialog: "Add unimplemented methods".

Thanks

Dj Boris
  • 189
  • 1
  • 2
  • 10

5 Answers5

23

How can I write a method and force the subclasses to override this method.

Declare the method as abstract:

enter image description here

Eclipse will give you the "Add unimplemented methods"-option for all (unimplemented) abstract methods and interface methods.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Not a general answer. A class with an abstract method can't be instantiated. (only it's sub-classes can) – Mark Jeronimus Dec 24 '22 at 18:10
  • An abstract class is instantiated when its subclass is instantiated. – aioobe Dec 24 '22 at 18:53
  • I meant that I have instances of both the base class and subclasses, and both need an actual implementation of a method, but subclasses must be enforced to override the base class implementation. – Mark Jeronimus Dec 25 '22 at 10:51
  • @MarkJeronimus, do you mean that you _have_ an implementation in the base class, but still want to require subclasses to implement (override) the method? – aioobe Dec 25 '22 at 11:37
  • Yes. Although I eventually settled on making a separate base class that isn't polymorphically connected – Mark Jeronimus Dec 26 '22 at 18:56
8

Just declare the method as abstract in the base class. All children classes will then be forced to implement it. Alternatively you could also use an interface instead of a concrete class, which is simply an agreement that the methods defined will be implemented. Either one is fine, it depends on your needs.

Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
4

You can do that by making the method abstract (not providing a default implementation).

rsp
  • 23,135
  • 6
  • 55
  • 69
3

Or if you do NOT want your class to be an abstract class, you can throw your own MustOverrideException at the method that you want to force to be overridden.

Lemuel Adane
  • 55
  • 1
  • 1
  • 8
2

Declare the method as abstract.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680