从子类访问父类的私有实例变量? [英] Accessing private instance variables of parent from child class?

查看:201
本文介绍了从子类访问父类的私有实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个类 foo ,它有一个私有实例变量 bar

Let's say we have a class foo which has a private instance variable bar.

现在让我们有另一个班级, baz ,其中扩展foo baz 中的非静态方法可以访问 foo 的变量 bar 如果 foo 中没有定义访问者方法?

Now let us have another class, baz, which extends foo. Can non-static methods in baz access foo's variable bar if there is no accessor method defined in foo?

顺便说一句,我在Java工作。

I'm working in Java, by the way.

推荐答案

不,不是根据 java语言规范,第3版


6.6.8示例:私有字段,方法和构造函数

私有
类成员或构造函数是
只能在
顶级类(第7.6节)的主体内访问,该类包含
成员或
构造函数的声明。它不是由
子类继承的。

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses.

但不管这种语言限制,你可以 通过反思访问私人字段

But regardless of this language restriction, you can access private fields through reflection:

Field privateStringField = 
   MyClass.class.getDeclaredField("privateString");
privateStringField.setAccessible(true);

String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);

这篇关于从子类访问父类的私有实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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