如何防止 Java 中的方法被重写?
java 8object oriented programmingprogramming
继承可以定义为一个(父/超)类获取另一个(子/子)类的成员(方法和字段)的过程。
如果两个类通过继承相互关联。如果超类和子类包含相同的方法(相同的名称和参数),当我们使用子类对象调用它时,将执行子类的方法。这种机制称为重写。
重写 final 方法
一旦将方法声明为 final,它就无法被重写。如果您尝试这样做,它将生成编译时错误 −
示例
class Super{ public final void demo() { System.out.println("This is the method of the superclass"); } } class Sub extends Super{ public final void demo() { System.out.println("This is the method of the subclass"); } }
编译时错误
Sub.java:7: error: demo() in Sub cannot override demo() in Super public final void demo() { ^ overridden method is final 1 error
如果您尝试在 eclipse 中编译相同的程序,您将收到以下错误 −
因此,如果您想防止方法被覆盖,只需将其声明为 final。