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?
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.
@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.
No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With