What is the point of the "static method declared final" inspection?

Static final methods trigger the following warning:

'static' method declared 'final'


Reports methods declared final and static. When a static method is overriden in a subclass it can still be accessed via the superclass making the final declaration not very necessary. Declaring a static method final does prevent subclasses from defining a static method with the same signature.


This makes it look like it's  bad practice for static methods to also be declared final, but that's not true, the two qualifiers are orthogonal. If you don't want the method to be overriden you declare it final and that's it.

I know that I can simply disable the warning, but I'm wondering what was the original thinking behind it.
3 comments
Comment actions Permalink

What exactly would you like to express by attaching "final" to a static method?

As the explanation says, you just cannot "override" a static method.
Usually you call a static method using its class: SomeClass.staticMethod().
So even if you declare the method final, a sub class could still define the same method and you could call SomeSubClass.staticMethod().

If the same static method (i.e. a method with the same signature) is declared in both a class and a subclass, then if you do use an instance variable to call the method:
someInstance.staticMethod()
then the method will be selected by the _static_ (declared) type of the variable "someInstance". There is no polymorphism.

Also see
http://c2.com/cgi/wiki?StaticMethodsNonPolymorphic

0
Comment actions Permalink

You made the same mistake I originally did when seeing this warning:

So even if you declare the method final, a sub class could still define the same method and you could call SomeSubClass.staticMethod().

No, if the method is declared final then a subclass could not re-define it, you'd get a compilation error. And this is precisely what the intention of final is: to prevent sub-classes from re-defining the method. It's a perfectly valid construct and it's confusing to have it be highlighted as a warning  by default.

0
Comment actions Permalink

Oops, right.

I guess the argument should be read as:
Inheritance of static methods does not make much sense any way, because there's no polymorphism.
If overriding is useless, then it does not make much sense to make a special case for not allowing overriding.

(Not that I really agree with that.)

0

Please sign in to leave a comment.