我一直在玩弄带有静态方法的修饰符,并遇到了一个奇怪的行为。
正如我们所知,静态方法不能被覆盖,因为它们与类而不是实例相关联。
所以如果我有下面的代码片段,它编译得很好
//Snippet 1 - Compiles fine
public class A {
static void ts() {
}
}
class B extends A {
static void ts() {
}
}
但是,如果我在类 A 中将 final 修饰符包含在静态方法中,则编译失败 ts() in B 无法覆盖 ts() in A;重写的方法是 static final 。
当根本无法覆盖静态方法时,为什么会发生这种情况?
原文由 Harish 发布,翻译遵循 CC BY-SA 4.0 许可协议
静态方法不能被重写,但可以隐藏。 B 的
ts()
方法没有覆盖(不受多态性影响)A 的ts()
但它会隐藏它。 If you callts()
in B (NOTA.ts()
orB.ts()
… justts()
), the one of B will be called and不是 A。因为这不受多态性影响,所以 A 中的调用ts()
永远不会被重定向到 B 中的调用。关键字
final
将禁止方法被隐藏。因此它们不能被隐藏,并且尝试这样做将导致编译器错误。希望这可以帮助。