[英]How can I gain access to a parent class's private variable?
I understand that private variables aren't inherited, so how can I gain access to it in my subclass? 我知道私有变量不会被继承,那么如何在子类中访问它呢?
ie 即
class A{
private int i = 5;
// more code
}
class B extends A{
public int toInt(){
return super.i;
}
}
Normally you'd mark i
as protected
which allows sub-classes to see the field. 通常,您会将
i
标记为protected
,这允许子类查看该字段。
Another approach is to write a get
-style function, which sometimes can be better especially if you want to disallow sub-classes from writing to the field. 另一种方法是编写一个
get
样式的函数,该函数有时会更好,特别是如果您要禁止子类写入字段。 Writing a put
-style function really defeats encapsulation. 编写
put
样式的函数确实会破坏封装。
Reflection also offers another way of circumventing private
, but using that approach is not to be recommended. 反思还提供了另一种规避
private
,但是不建议使用该方法。
Generally you can't and should not. 通常,您不能也不应。 This is the reason that the variable is
private
. 这就是该变量为
private
的原因。
If you want to implement your base class to allow its subclasses to get access to the private members implement protected
accessor methods (either getters or setters). 如果要实现基类以允许其子类访问私有成员,请实现
protected
访问器方法(getter或setter)。 You can also mark the fields as protected
but I do not recommend even to start with it. 您也可以将字段标记为
protected
但我什至不建议您从此开始。 You need very serious reason to make non-private fields. 您需要非常认真的理由来设置非私有字段。
The "workaround" that is possible in java is using reflection API: Java中可能的“解决方法”是使用反射API:
Field f = A.class.getDeclaredField("i");
f.setAccessible(true);
f.get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.