Reputation: 4706
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?
Upvotes: 38
Views: 13342
Reputation: 22171
If your method is not part of your builded API and isn't directly called by subclasses, prefer simply making your method private
.
If your class hierarchy is contained in a single package, make your method in package scope (without keyword of scoping). Thus, only outside world (included your other own packages) can't access it and therefore can't override it.
If your method isn't really part of your API but has to be visible by subclasses even external, prefer make it protected
and final
Finally if your method is part of your API, make it public
and final
.
Upvotes: 4
Reputation: 1496
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
Upvotes: 65