我們可以在 Java 中重寫 private 或 static 方法嗎
不可以,我們無法在 Java 中重寫 private 或 static 方法。
Java 中的 private 方法對其他類不可見,其作用域僅限於宣告它們的類。
示例
讓我們看看當嘗試重寫 private 方法時發生的情況 -
class Parent { private void display() { System.out.println("Super class"); } } public class Example extends Parent { void display() // trying to override display() { System.out.println("Sub class"); } public static void main(String[] args) { Parent obj = new Example(); obj.display(); } }
輸出
輸出如下 -
Example.java:17: error: display() has private access in Parent obj.method(); ^ 1 error
該程式會引發一個編譯時錯誤,表明 display() 在父類中具有 private 訪問許可權,因此無法在子類 Example 中被重寫。
如果某個方法被宣告為 static,則該方法是類的成員,而不是屬於類的物件。該方法可以在不建立類物件的情況下呼叫。靜態方法還可以訪問類的靜態資料成員。
示例
讓我們看看當我們嘗試在一個子類中重寫一個 static 方法時發生的情況
class Parent { static void display() { System.out.println("Super class"); } } public class Example extends Parent { void display() // trying to override display() { System.out.println("Sub class"); } public static void main(String[] args) { Parent obj = new Example(); obj.display(); } }
輸出
這會生成一個編譯時錯誤。輸出如下 -
Example.java:10: error: display() in Example cannot override display() in Parent void display() // trying to override display() ^ overridden method is static 1 error
廣告