How to force a method to be overridden in java?

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

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();

Solution 4 - Java

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.

Solution 5 - Java

Make this method abstract.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHari MenonView Question on Stackoverflow
Solution 1 - JavaPablo Santa CruzView Answer on Stackoverflow
Solution 2 - JavaJens HoffmannView Answer on Stackoverflow
Solution 3 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 4 - JavaBuhake SindiView Answer on Stackoverflow
Solution 5 - JavavitautView Answer on Stackoverflow