我可以从抽象超类上的方法访问子类上定义的静态成员变量吗?
我有一个带有单个具体方法的抽象类。在此方法中,我想使用从声明该方法的类派生的类中的静态类变量。为此,我当然也必须在抽象类中声明此静态变量。
当调用该方法时,变量将解析为我的抽象基类中的变量,而不是派生类中的变量。我需要用属性来修饰派生类的属性吗?
我是否正在尝试做一些Java不支持的事情,或者我只是错过了什么?
I have an abstract class with a single concrete method. In this method I want to use a static class variable from the classes that derive from the one the method is declared in. To do so, I of course have to declare this static variable in the abstract class as well.
When the method is called, the variable is resolved to the one in my abstract base class as opposed to the one in the derived class. Do I need to decorate the derived class' property with an attribute?
Am I trying to do something that is not supported in Java, or am I just missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在尝试做一些不受支持的事情。字段不能被“覆盖” - 并且静态成员的行为不具有多态性。
相反,创建可以在派生类中实现的抽象属性。即使它们返回静态变量,它们也必须是实例属性。
You're trying to do something that isn't supported. Fields can't be "overridden" - and static members don't behave polymorphically.
Instead, create abstract properties which can be implemented in the derived classes. They'll have to be instance properties even if they return static variables.
您不能覆盖变量,只能覆盖方法。如果子类可能需要提供不同的值,请向执行此操作的类添加 getter 方法。
You can't override variables, only methods. If its likely that a subclass needs to give a different value, add a getter method to the class that does that.
根据您想要执行的操作,您可以执行以下操作:
,但您可能需要 Jon 的方法。
Depending on what you want to do, you can do:
, but you likely want Jon's approach.