在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
广告