38

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?

John
  • 4,596
  • 11
  • 37
  • 43

3 Answers3

63

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

yotommy
  • 1,472
  • 1
  • 12
  • 17
  • This is so obvious, why didn't I think of this? – xorinzor Sep 07 '17 at 23:12
  • Can cause Problems when using 'JavassistLazyInitializer'. https://forum.hibernate.org/viewtopic.php?f=1&t=997278 – Pwnstar Mar 22 '18 at 09:26
  • Beware, it will cause issues with Spring `@Component`: child class is a `@Component` that inherits from the non-component parent class and this parent class has at least one `final` method. This method will not be wrapped into proxy object and might throw an exception when working with properties that should have been initialized with non-null values, so you might get a `NullPointerException`. – izogfif Jun 17 '20 at 14:37
9

Simply make the method final.

s.s.o
  • 175
  • 6
4

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.

Mik378
  • 21,881
  • 15
  • 82
  • 180