Dj Boris
Dj Boris

Reputation: 199

Java: Force subclasses to override methods of the Superclass

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

Upvotes: 13

Views: 15104

Answers (5)

aioobe
aioobe

Reputation: 420991

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.

Upvotes: 23

Lemuel Adane
Lemuel Adane

Reputation: 55

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.

Upvotes: 3

rsp
rsp

Reputation: 23373

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

Upvotes: 4

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

Declare the method as abstract.

Upvotes: 2

Chris Eberle
Chris Eberle

Reputation: 48775

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.

Upvotes: 8

Related Questions