Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a method to be overridden in java?

Tags:

java

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?

like image 667
Hari Menon Avatar asked Nov 17 '10 11:11

Hari Menon


People also ask

Does @override in Java do anything?

The @Override annotation is one of a default Java annotation and it can be introduced in Java 1.5 Version. The @Override annotation indicates that the child class method is over-writing its base class method. It extracts a warning from the compiler if the annotated method doesn't actually override anything.

Do you need @override to override in Java?

@Override annotation is used when we override a method in sub class. Generally novice developers overlook this feature as it is not mandatory to use this annotation while overriding the method.

Can method be overridden?

No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.

When it is mandatory to override a method in Java?

In some cases, method overriding is mandatory - if you implement an interface, for example, you must override its methods. Yet, in others, it is usually up to the programmer to decide whether they will override some given methods or not. Take a scenario where one extends a non-abstract class, for instance.


2 Answers

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.

like image 82
Pablo Santa Cruz Avatar answered Sep 20 '22 10:09

Pablo Santa Cruz


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.

like image 42
Jens Hoffmann Avatar answered Sep 23 '22 10:09

Jens Hoffmann