Suppose I have a method in a Java class, and I don't want any subclass of that class to be able to override that method. Can I do that?
You can prevent a class from being subclassed by using the final keyword in the class's declaration. Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method. An abstract class can only be subclassed; it cannot be instantiated.
The final way of preventing overriding is by using the final keyword in your method. The final keyword puts a stop to being an inheritance. Hence, if a method is made final it will be considered final implementation and no other class can override the behavior.
1. Using final keyword to prevent method overriding during inheritance: All methods and variables can be overridden by default in a subclasses.
You can declare the method to be final
, as in:
public final String getId() { ... }
For more info, see http://docs.oracle.com/javase/tutorial/java/IandI/final.html
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