防止子 class 覆盖父中的方法

Prevent child class from overriding a method in parent

我有一个主classRecordFieldBase。应用程序中有许多从 RecordFieldBase class 扩展而来的子class。基础 RecordFieldBase class 公开了 public 方法 updateInspector,它看起来像这样:

public Inspector udpateInspector {
  if () {
    return this.getBasicInspector();
  } else {
    return this.getValidationInspector();
  }
}

应用程序将在子 RecordField 实例上调用 updateInspector 以获取 Inspector 实例。每个 subclass 都可以有自定义的基本和验证检查器。他们可以使用 getBasicInspectorgetValidationInspector 方法来实现它,但他们不能覆盖基础 class 的 updateInspector,因为它包含处理逻辑。

在这里使用 final 关键字合适吗?

public final Inspector udpateInspector {
  if (some check here) {
    return this.getBasicInspector();
  } else {
    return this.getValidationInspector();
  }
}

是的,这正是 java 对方法使用 final 修饰符的原因。

是的...看看文档...

https://docs.oracle.com/javase/tutorial/java/IandI/final.html

final 方法的想法是阻止从子 类...

覆盖它