有多少种方法可以防止 Java 中的方法重写?

javaobject oriented programmingprogramming更新于 2024/5/12 1:32:00

方法重写之所以有效,是因为 Java 中的运行时方法绑定功能。因此,如果我们强制 Java 编译器对方法进行静态绑定,那么我们就可以防止该方法在派生类中被重写。

我们可以通过 3 种方式防止 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");
   }
   // 无法覆盖 test() 方法,因为它在 Base 类中是 final
   /*
   *  public void test() { System.out.println("Derived class test() method"); }
   */
}
public class Test {
   public static void main(String[] args) {
      Base ref = new Derived();
   // 调用最终方法 test()
      ref.test();
   // 调用重写的方法 show()
      ref.show();
   }
}

输出

Base class test() method
Derived class show() method

静态方法不能被覆盖

我们不能覆盖派生类中的静态方法,因为静态方法是与类链接的,而不是与对象链接的。这意味着当我们调用静态方法时,JVM 不会像对待所有非静态方法那样将此引用传递给它。因此静态方法不能进行运行时绑定。

示例

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");
   }
      // 这不是重写的方法,这将被视为 Derived 类中的新方法
   public static void test() {
      System.out.println("Derived class test() method");
   }
}
public class Test {
   public static void main(String[] args) {
      Base ref = new Derived();
      // 它将调用 Base 类的 test(),因为它具有静态绑定
      ref.test();
      // 调用重写的方法 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");
   }
   // 这不是重写的方法,将被视为其他方法。
   public void test() {
      System.out.println("Derived class test() method");
   }
}
public class Test {
   public static void main(String[] args) {
      Base ref = new Derived();
   // 无法调用私有方法 test(),此行将给出编译时错误
   // ref.test();
   // 调用重写的方法 show()
      ref.show();
   }
}

输出

Derived class show() method

相关文章