在Java中,防止方法覆蓋有多少種方法?
**方法覆蓋**之所以能夠工作,是因為Java中的執行時方法繫結特性。因此,如果我們強制Java編譯器對方法進行靜態繫結,那麼我們可以防止該方法在派生類中被覆蓋。
我們可以透過三種方法在Java中防止方法覆蓋
- 在基類中將方法宣告為final
- 在基類中將方法宣告為static
- 在基類中將方法宣告為private
final方法不能被覆蓋
透過將方法宣告為final,我們添加了一個限制,即派生類不能覆蓋此特定方法。
示例
class Base {
public void show() {
System.out.println("Base class show() method");
}
public final void test() {
System.out.println("Base class test() method");
}
}
class Derived extends Base {
public void show() {
System.out.println("Derived class show() method");
}
// can not override test() method because its final in Base class
/*
* public void test() { System.out.println("Derived class test() method"); }
*/
}
public class Test {
public static void main(String[] args) {
Base ref = new Derived();
// Calling the final method test()
ref.test();
// Calling the overridden method show()
ref.show();
}
}輸出
Base class test() method Derived class show() method
靜態方法不能被覆蓋
我們不能在派生類中覆蓋靜態方法,因為靜態方法與類相關聯,而不是與物件相關聯。這意味著當我們呼叫靜態方法時,JVM不會像對所有非靜態方法那樣傳遞this引用。因此,執行時繫結不能對靜態方法進行。
示例
class Base {
public void show() {
System.out.println("Base class show() method");
}
public static void test() {
System.out.println("Base class test() method");
}
}
class Derived extends Base {
public void show() {
System.out.println("Derived class show() method");
}
// This is not an overridden method, this will be considered as new method in Derived class
public static void test() {
System.out.println("Derived class test() method");
}
}
public class Test {
public static void main(String[] args) {
Base ref = new Derived();
// It will call the Base class's test() because it had static binding
ref.test();
// Calling the overridden method show()
ref.show();
}
}輸出
Base class test() method Derived class show() method
私有方法不能被覆蓋
基類的私有方法在派生類中不可見,因此它們不能被覆蓋。
示例
class Base {
public void show() {
System.out.println("Base class show() method");
}
private void test() {
System.out.println("Base class test() method");
}
}
class Derived extends Base {
public void show() {
System.out.println("Derived class show() method");
}
// This is not an overridden method, this will be considered as other method.
public void test() {
System.out.println("Derived class test() method");
}
}
public class Test {
public static void main(String[] args) {
Base ref = new Derived();
// Cannot call the private method test(), this line will give compile time error
// ref.test();
// Calling the overridden method show()
ref.show();
}
}輸出
Derived class show() method
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP