[英]what is the use of inheriting a final method in java ? If we cant override it
I was studying about java basics and came across this final keyword.我正在研究 java 基础知识并遇到了这个最终关键字。 And read that a final method can be inherited.
并阅读可以继承最终方法。 But we cant override that method.
但是我们不能覆盖那个方法。 Then what is use of inheriting any final method?
那么继承任何 final 方法有什么用呢? why to do that?
为什么要这样做?
Inheritance of a method makes that method available for calling in a subclass.方法的 Inheritance 使该方法可用于在子类中调用。 Calling a method is obviously useful.
调用方法显然很有用。
When a method name is called on a subclass, the Java runtime looks first to see if the subclass has such a method.当在子类上调用方法名时,Java 运行时首先查看子类是否有这样的方法。 If found, that implementation of the method is executed.
如果找到,则执行该方法的实现。 If not found, the Java runtime then looks to the superclass for such a method.
如果未找到,则 Java 运行时会在超类中查找此类方法。 If found, that implementation of the method is executed.
如果找到,则执行该方法的实现。 If not found, the Java runtime looks to the superclass of the superclass, and so on.
如果未找到,则 Java 运行时会查找超类的超类,依此类推。
Overriding means you do not want to call the method in the superclass, and instead the subclass provides an alternative (or additional) behavior to be used when that method name is invoked.覆盖意味着您不想调用超类中的方法,而是子类提供了在调用该方法名称时使用的替代(或附加)行为。 In some classes, allowing alternative/additional behavior may be risky.
在某些课程中,允许替代/附加行为可能是有风险的。
Indeed, general opinion seems to be evolving towards the position that all methods should be final until the class author has determined a case where permitting specific overrides is necessary or useful enough to justify the potential risk.事实上,一般意见似乎正在向 position 发展,即所有方法都应该是最终的,直到 class 作者确定允许特定覆盖是必要或有用的情况以证明潜在风险是合理的。 (A similar wisdom seems to be growing, in the position that classes should be initially designed as immutable until a specific need for mutability has been established.)
(类似的智慧似乎正在增长,在 position 中,类应该最初设计为不可变的,直到确定了对可变性的特定需求。)
The future feature of sealed classes/interfaces puts another spin on the issue.密封类/接口的未来特性为这个问题带来了另一个变化。 A sealed class allows inheritance only by an explicit list of subclasses known at compile-time.
密封的 class 仅通过编译时已知的子类的显式列表允许 inheritance。
In a sealed class, a method can be available for inheritance (non- final
) only by its known subclasses.在密封的 class 中,仅通过其已知子类可以为 inheritance(非
final
)提供一种方法。 The risk of unintended behavior being added later by other classes is eliminated by the compiler and the Java runtime environment respecting the list of allowed subclasses.编译器和 Java 运行时环境尊重允许的子类列表,消除了其他类稍后添加意外行为的风险。
You can try sealed classes as a preview feature now in Java 16 .您现在可以在 Java 16 中尝试将密封类作为预览功能。 The feature is due for release in Java 17 coming 2021-09.
该功能将于 2021 年 9 月在 Java 17中发布。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.