子类需要访问抽象超类的私有属性
我有一个抽象 java 类,它实现了它的几个方法,但没有实现其他方法。在它实现的方法中,它使用私有属性变量。使用的变量也需要在子类中使用。
在我看来,我的选择是:
- 在子类和超类中声明私有变量,
- 将抽象类中当前实现的方法的实现推迟到子类
还有其他选择吗?其中哪一个更有意义?为什么?
I have an abstract java class that implements a couple of its methods, but not others. In the methods it implements it uses a private attribute variable. The variable used also needs to be used in a subclass.
As I see it my options are:
- Declare the private variable in both the subclass and the super class
- defer the implementation of the methods currently implemented in the abstract class to the subclasses
Are there other options? Which of these makes more sense and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是你想如何维护你的状态:如果不关心值的存储位置,你可以只在另一个成员的“顶部”添加一个
private
成员,然后使用它来代替超类中的那个。如果您希望超类中的某些方法和子类中的某些方法访问相同的状态,则需要更改可见性:您可以将变量声明为“受保护”,使其在子类中可访问,或实现访问器方法,甚至使其
公开
。The question is how you want to maintain your state: If it is of no concern, where the value is stored, you can just add a
private
member "on top" of the other and use that instead of the one in the superclass. If you want to have some methods from your superclass and some methods from your subclass to access the same state, you need to change visibility:You could declare the variable as
protected
, making it accessible in the subclass, or implement accessor methods, or even make itpublic
.希望抽象类的设计使得您不需要访问私有字段。至于使用两种方法中的哪一种,这完全取决于抽象类和子类是什么以及它们应该做什么。
如果您只需要对此变量的读取访问权限,并且超类方法不修改它,则可以将另一个具有相同名称/类型的(完全独立的)私有字段添加到您的子类中。如果您尝试通过更改字段来修改超类方法的行为,则必须重写这些方法。
Hopefully the abstract class has been designed such that you shouldn't need access to the private fields. As to which of your two methods to use, that depends entirely on what the abstract class and your subclass are and what they're supposed to be doing.
If you only need read access to this variable and the superclass methods don't modify it, you can just add another (completely separate) private field of the same name/type to your subclass. If you're attempting to modify the behaviour of the superclass methods by changing the field, you're going to have to override the methods instead.