You might find yourself in the position to think about making a static method final, considering the following:
Having the following classes:
class A {
static void ts() {
System.out.print("A");
}
}
class B extends A {
static void ts() {
System.out.print("B");
}
}
Now the correct way to call these methods would be
A.ts();
B.ts();
which would result in AB
but you could also call the methods on instances:
A a = new A();
a.ts();
B b = new B();
b.ts();
which would result in AB
as well.
Now consider the following:
A a = new B();
a.ts();
that would print A
. That might surprise you since you are actually having an object of class B
. But since you re calling it from a reference of type A
, it will call A.ts()
. You could print B
with the following code:
A a = new B();
((B)a).ts();
In both cases the object you have is actually from class B
. But depending on the pointer that points to the object, you will call method from A
or from B
.
Now let s say you are the developer of class A
and you want to allow sub-classing. But you really want method ts()
, whenever called, even from a subclass, that is does what you want it to do and not to be hidden by a subclass version. Then you could make it final
and prevent it from being hidden in the subclass. And you can be sure that the following code will call the method from your class A
:
B b = new B();
b.ts();
Ok, admittetly that is somehow constructed, but it might make sense for some cases.
You should not call static methods on instances but directly on the classes - then you won t have that problem. Also IntelliJ IDEA for example will show you a warning, if you call a static method on an instance and as well if you make a static method final.