简体   繁体   English

如何获得对父类的私有变量的访问权限?

[英]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.

相关问题 我如何从另一个类访问对象变量? - How do I gain access to an objects variable from another class? 我如何访问另一个class中的父字段并更改它? - How can I access the parent's field in another class and change it? 如何访问 class 的私有构造函数? - How can I access a private constructor of a class? 创建自定义视图:如何扩展类并访问基类的私有成员变量? - Creating a custom view: how can I extend a class and access the base class's private member variables? 为什么我可以从 Class 外部访问私有变量? - Why Can I Access Private Variable From Outside Class? 如何在Android的另一个班级中访问选定的列表项 - How can i gain access to the selected list item in another class in android 如何使用 getter 函数访问另一个类中的私有变量? - How can access to a private variable in another class by using a getter function? 如何从父类访问私有字段 - How to access private fields from parent class 子类对象如何访问父类的私有变量,就像java中一样,除了类本身可以访问私有变量之外,否? - How does the subclass object access the private variable of super class,as in java no except the class itself can access the private variable? 可变访问私人班级 - Variable access to private class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM