Hiding-Static-Methods
最近,我和一位同事在同一個簽名的父類和子類中就靜態(tài)方法進行了一次快速聊天址否。對話的來源是術語“隱藏”與“覆蓋”泽篮,以及為什么“隱藏靜態(tài)方法”是正確的并且可行,但“覆蓋靜態(tài)方法”是不正確的并且不起作用麸祷。
TL; DR“不能覆蓋靜態(tài)方法”澎怒,因為JVM在聲明的引用類上執(zhí)行靜態(tài)方法褒搔,而不是定義的運行時/實例類。
一個簡單的例子展示了幾種不同的靜態(tài)方法執(zhí)行上下文喷面,說明了結果:
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í)行結果星瘾。結果表明,被調用的靜態(tài)方法是定義參考的方法惧辈。
將Child 作為Java應用程序(主要方法)輸出:
PARENT
PARENT
CHILD
CHILD
這與使用更正確的靜態(tài)引用調用替換實例方法調用沒有區(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