[英]Prevent child class from overriding a method in parent
I have a main class RecordFieldBase
. 我有一个主类
RecordFieldBase
。 There many subclasses in the application that extend from RecordFieldBase
class. 应用程序中有许多子类是从
RecordFieldBase
类扩展而来的。 The base RecordFieldBase
class exposes public method updateInspector
, it looks like this: RecordFieldBase
基类公开了公共方法updateInspector
,如下所示:
public Inspector udpateInspector {
if () {
return this.getBasicInspector();
} else {
return this.getValidationInspector();
}
}
The application will call updateInspector
on the child RecordField
instances to get an instance of Inspector. 该应用程序将在子
RecordField
实例上调用updateInspector
以获取Inspector的实例。 Each subclass can have custom basic and validation inspectors. 每个子类可以具有自定义的基本检查器和验证检查器。 They can implement it using
getBasicInspector
and getValidationInspector
methods, but they must not override updateInspector
of the base class as it contains the handling logic. 他们可以使用
getBasicInspector
和getValidationInspector
方法来实现它,但是它们不能覆盖基类的updateInspector
,因为它包含处理逻辑。
Is using final
keyword appropriate here? 在这里使用
final
关键字合适吗?
public final Inspector udpateInspector {
if (some check here) {
return this.getBasicInspector();
} else {
return this.getValidationInspector();
}
}
是的,这正是Java对方法使用final修饰符的原因。
yes... take a look at the doc... 是的...看一下文档...
https://docs.oracle.com/javase/tutorial/java/IandI/final.html https://docs.oracle.com/javase/tutorial/java/IandI/final.html
the idea of final methods is to block overriding it from child classes... 最终方法的思想是阻止从子类中覆盖它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.