Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disallow subclasses from overriding Java method

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?

like image 611
John Avatar asked Oct 22 '12 23:10

John


People also ask

How can we avoid overriding from subclass in Java?

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.

How do you stop a subclass overriding?

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.

What keyword prevents subclasses from overriding a method?

1. Using final keyword to prevent method overriding during inheritance: All methods and variables can be overridden by default in a subclasses.


1 Answers

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

like image 81
yotommy Avatar answered Oct 11 '22 11:10

yotommy