John
John

Reputation: 4706

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?

Upvotes: 38

Views: 13342

Answers (3)

Mik378
Mik378

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

s.s.o
s.s.o

Reputation: 185

Simply make the method final.

Upvotes: 10

yotommy
yotommy

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

Related Questions