IDEA 对static和final连用的警告问题

在复现设计模式-单例模式-静态内部类的时候,IDEA给出了警告

短提示如下

'static' 方法被声明为 'final'

详细提示为

'static' 方法被声明为 'final'
Inspection info: Reports methods declared final and static. When a static method is overridden in a subclass it can still be accessed via the super class, making a final declaration not very necessary. Declaring a static method final does prevent subclasses from defining a static method with the same signature.

网上一大堆的文章或者说法,都是说staticfinal一般是连用的。这就有一点冲突了。

查了一下,发现官方的说法是这样的,链接:https://intellij-support.jetbrains.com/hc/en-us/community/posts/206822805-What-is-the-point-of-the-static-method-declared-final-inspection-

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.

划重点:As the explanation says, you just cannot "override" a static method.

将一个方法声明为final,是防止该类被子类重写。但是static方法本身就不可被重写。这是最关键的地方。因此对于一个static方法来说,加上final其实是啰嗦多余。
所以IDEA就给了Warning。现在看来就可以理解了。

You may also like...

发表评论

电子邮件地址不会被公开。 必填项已用*标注