在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, 就酱~