java中的最终字段继承
是否可以让给定的子类初始化其超类中的静态最终字段?本质上,我希望子类配置所需的类范围变量。不幸的是,abstract关键字并不完全适用于字段。
Is it possible to have a given subclass initialize static final fields in its superclass? Essentially I would like for the subclass to configure required class-wide variables. Unfortunately, the abstract keyword doesn't exactly work with fields..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不 - 如果有两个子类试图做同样的事情,你会期望它如何工作?如果您有静态最终字段,则它们必须由声明它们的类初始化。
如果您尝试同时使用静态字段和继承,那么老实说,这通常是一个错误的迹象 - 它们是两个概念,通常不能很好地结合在一起。人们经常尝试使用静态方法等来“伪造”继承,并且通常会以糟糕的方式结束 - 这听起来像是该主题的变体。
如果您能描述一下您的更广泛的情况,我们也许能够为您提供更多帮助。顺便说一句,为了可测试性,我强烈建议您一般避免使用静态。它们对于真正的常量来说很好,但是如果它是类似配置的东西,那么在构造对象时传递相关设置会更好(IMO)。
编辑:我可以看到四个选项可以更好地模拟您的情况:
maxHealth
设为方法,这样您就可以询问任何玩家的最大生命值是多少 中分别重写Model
Player
和PlayerClass
:这样,您可以在“玩家类”级别继承,但您不必这样做 - 您可以创建多个
PlayerClass
实例,其行为 以同样的方式,但具有不同的统计数据...或者您可以子类化PlayerClass
以提供自定义行为。那时,您可能根本不需要Player
的不同子类。与想法 3 相同,但使用枚举:
我怀疑,就我个人而言,我的偏好将是最终选择。您仍然可以覆盖行为,但是您有一组固定的可能类 - 这可能相当准确地对您的游戏进行建模。
No - how would you expect it to work if there were two subclasses which tried to do the same thing? If you've got static final fields, they must be initialized by the class which declares them.
If you're trying to use static fields and inheritance together, that's usually a sign that something's wrong to start with, to be honest - they're two concepts which generally don't play well together. People often try to "fake" inheritance with static methods etc, and it usually ends badly - this sounds like a variation on that theme.
If you can describe your broader picture, we may be able to help you more. I would urge you to avoid statics in general for the sake of testability, by the way. They're fine for genuine constants, but if it's anything like configuration, it's nicer to pass in relevant settings when constructing an object (IMO).
EDIT: I can see four options which would model your situation better:
maxHealth
a method, so you can ask any player what their maximum health is - that's then polymorphic, so can be overridden in each classModel
Player
andPlayerClass
separately:That way you can have inheritance at the "player class" level, but you don't have to - you could create several
PlayerClass
instances which behave the same way, but have different stats... or you could subclassPlayerClass
to give custom behaviour. At that point you may not need different subclasses ofPlayer
at all.The same as idea 3, but using an enum:
Personally my preference would be the final option, I suspect. You can still override behaviour, but you have a fixed set of possible classes - which probably models your game reasonably accurately.
关于 Jon Skeet 的回答,我认为“如果您尝试同时使用静态字段和继承”,这并没有那么糟糕。我建议你使用注释:
Regarding Jon Skeet's answer, I don't think it's that bad "If you're trying to use static fields and inheritance together". I suggest you to use annotations: