简体   繁体   中英

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.

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. Writing a put -style function really defeats encapsulation.

Reflection also offers another way of circumventing private , but using that approach is not to be recommended.

Generally you can't and should not. This is the reason that the variable is 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). You can also mark the fields as protected but I do not recommend even to start with it. You need very serious reason to make non-private fields.

The "workaround" that is possible in java is using reflection API:

Field f = A.class.getDeclaredField("i");
f.setAccessible(true);
f.get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM