Java中最终字段的继承? [英] Inheritance of final fields in Java?

查看:409
本文介绍了Java中最终字段的继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当超类的字段标记为final时会发生什么,但子类会覆盖(隐藏?)此字段? 最终不会阻止这一点,是吗?
我正在研究的具体例子是建筑类,不同类型的建筑物从中继承。除其他外,每种类型的成本应该是每个子类的最终成本,但每种类型的建筑物都应该有自己的成本。

What happens when a superclass has a field marked final, but a subclass overrides (hides?) this field? 'Final' doesn't stop this, does it? The specific example I'm working on is a Building class, from which different kinds of buildings inherit. The cost of each type, among other things, should be final to each subclass, but each type of building should have their own cost.

编辑:我已经实现了我不知道上面说的是什么。我真正想要的是成本的静态变量。但是,如果我在超类中声明这些静态变量,它们对于超类是静态的,因此Subclass1.cost例如引用与Superclass.cost或Subclass2.cost相同的值。如何为每个子类创建静态变量,而不必在每个类中声明它们。

I've since realized that I had no idea what I was talking about above. What I really want are static variables of cost. However, if I declare these static variables in the superclass, they are static to the superclass, so Subclass1.cost, e.g., refers to the same value as Superclass.cost or Subclass2.cost. How can I make variables that are static to each subclass, without having to declare them in each class.

推荐答案

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).

希望这会有所帮助!

这篇关于Java中最终字段的继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆