子类需要访问抽象超类的私有属性 [英] subclass needs access to private attribute of abstract superclass

查看:170
本文介绍了子类需要访问抽象超类的私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象的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.

我看到它的选项是:


  • 在子类和超类中声明私有变量

  • 将当前在抽象类中实现的方法的实现推迟到子类

还有其他选择吗?哪一个更有意义?为什么?

Are there other options? Which of these makes more sense and why?

推荐答案

问题是你想如何维持你的状态:如果它不是关注,存储值的地方,你可以在另一个上面添加一个 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:

你可以将变量声明为 protected ,使其可以在子类中访问,或实现访问器方法,甚至使其成为 public

You could declare the variable as protected, making it accessible in the subclass, or implement accessor methods, or even make it public.

这篇关于子类需要访问抽象超类的私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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