且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中最终字段的继承?

更新时间:2023-11-19 23:05:04

final 关键字,当应用于Java类的字段时,与继承无关。相反,它表示在构造函数之外,该字段无法重新分配。

The final keyword, when applied to fields of a Java class, has nothing to do with inheritance. Instead, it indicates that outside of the constructor, that field cannot be reassigned.

Java分别处理名称隐藏和覆盖。覆盖实际上通过切换调用哪个函数来改变程序在运行时的可观察行为,而名称隐藏通过更改正在引用哪个字段的静态解释来更改程序。应用于覆盖仅适用于方法的 final ,因为无法覆盖Java中的字段。不幸的是,在这些不同的上下文中使用 final 有点令人困惑,并且没有办法阻止字段隐藏在子类中。

Java treats name hiding and overriding separately. Overriding actually changes the observable behavior of the program at runtime by switching which function is called, while name hiding changes the program by changing the static interpretation of which field is being reference. final as applied to overriding only works for methods, because fields in Java cannot be overridden. The use of final in these different contexts is a bit confusing, unfortunately, and there is no way to prevent a field from having its name hidden in a subclass.

如果您希望建筑物具有不同的成本,一种选择是覆盖 getCost 方法,该方法在每个方法中被不同地覆盖派生类。或者,您可以在存储成本的基类中有一个 protected private 字段,然后拥有每个子类直接设置此字段(如果这是 protected )或通过基类构造函数设置此字段(如果此字段为 private ) 。

If you want the buildings to have different costs, one option would be to have an overridden getCost method which is overridden differently in each derived class. Alternatively, you could have a single protected or private field in the base class that stores the cost, then have each subclass set this field either directly (if this is protected) or through a base class constructor (if this field is private).

希望这会有所帮助!