
Hiding-Static-Methods
最近,我和一位同事在同一個簽名的父類和子類中就靜態(tài)方法進行了一次快速聊天。對話的來源是術(shù)語“隱藏”與“覆蓋”,以及為什么“隱藏靜態(tài)方法”是正確的并且可行,但“覆蓋靜態(tài)方法”是不正確的并且不起作用。
TL; DR“不能覆蓋靜態(tài)方法”,因為JVM在聲明的引用類上執(zhí)行靜態(tài)方法,而不是定義的運行時/實例類。
一個簡單的例子展示了幾種不同的靜態(tài)方法執(zhí)行上下文,說明了結(jié)果:
package com.intertech.hidestaticmethod;
public class Parent {
public static void doSomething() {
System.out.println("PARENT");
}
}
public class Child extends Parent {
public static void doSomething() {
System.out.println("CHILD");
}
public static void main(final String[] args) {
final Parent parentAsParent = new Parent();
// calls parent's
parentAsParent.doSomething();
final Parent childAsParent = new Child();
// calls parent's
childAsParent.doSomething();
final Child childAsChild = new Child();
// calls child's
childAsChild.doSomething();
// same class static context (most local)
doSomething();
}
}
主要方法注釋說明執(zhí)行結(jié)果。結(jié)果表明,被調(diào)用的靜態(tài)方法是定義參考的方法。
將Child 作為Java應(yīng)用程序(主要方法)輸出:
PARENT
PARENT
CHILD
CHILD
這與使用更正確的靜態(tài)引用調(diào)用替換實例方法調(diào)用沒有區(qū)別:
public class Child extends Parent {
public static void doSomething() {
System.out.println("CHILD");
}
public static void main(final String[] args) {
// calls parent's
Parent.doSomething();
// calls parent's
Parent.doSomething();
// calls child's
Child.doSomething();
// same class static context (most local)
Child.doSomething();
}
}
希望這篇文章幫助解釋隱藏靜態(tài)方法 - 為什么我們不能重寫靜態(tài)方法,但我們可以隱藏靜態(tài)方法。
本文翻譯于 Hiding Static Methods