在IntelliJ中, 如果將一個方法定義成static final
的, IDE會有一個warning信息:static method declared final.
如下:
image.png
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.
不是特別理解為什么static
方法不能被定義成final
的, 或者說沒必要定義成final
的.
Google到了一個JetBrains官方的解釋:(需科學上網)
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.
static
方法是不能被重寫的. 我們知道, 重寫(Override
)是為了多態(PS:什么, 你已經忘記了多態是啥了?趕緊去復習!)服務的, 如果沒有實現多態, 重寫就沒有任何意義了. 這個問題下面有個回答這樣說:
Inheritance of static methods does not make much sense any way, because there's no polymorphism.
繼承一個static
方法沒有任何意義, 因為這里面沒有多態.
我們看一個例子就知道了:
public class TestOverride {
public static void main(String[] args) {
A a = new B();
a.foo();
}
}
class A {
public static void foo() {
System.out.println("A");
}
}
class B extends A {
public static void foo() {
System.out.println("B");
}
}
輸出是"A", a.foo()
調用的是A.foo()
方法, 不是B.foo()
, 這就很尷尬了, 我們來復習一下多態的定義:
所謂多態就是指程序中定義的引用變量所指向的具體類型和通過該引用變量發出的方法
調用在編程時并不確定,而是在程序運行期間才確定,即一個引用變量到底會指向哪個類的實例對象,
該引用變量發出的方法調用到底是哪個類中實現的方法,必須到程序運行期間才能決定。
因為在程序運行時才確定具體的類,這樣,不用修改源程序代碼,
就可以讓引用變量綁定到各種不同的類實現上,從而導致該引用調用的具體方法隨之改變,
即不修改程序代碼就可以改變程序運行時所綁定的具體代碼,讓程序可以選擇多個運行狀態,這就是多態性。
很明顯, 多態是運行期(Runtime
)的特性, 在上面的栗子里, a.foo()
調用的究竟是A.foo()
還是B.foo()
, 在編譯期就確定了, 這特么根本就不是多態. 事實上, A.foo()
和B.foo()
也沒有任何的繼承關系, 如果你強行在B.foo()
前面加上@Override
, IDE是會報錯的.
所以, 現在就很明確了, final
表示這個方法不能被復寫, 既然static
方法本來就不具備復寫的條件, 再加final
就顯得多余了, 所以IDE給了warning, 就醬~