有参考资料时可以进行Java私有字段访问吗? [英] Java private field access possible when having a reference?

查看:82
本文介绍了有参考资料时可以进行Java私有字段访问吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天遇到了以下奇怪功能-如果您在类A的主体中引用了类A中的对象,则可以访问该对象的私有字段-即:

I came across the following "strange" feature today - if you have a reference to an object from the class A in the body of the class A you can access the private fields of this object - i.e:

public class Foo{
   private int bar;
   private Foo foo;
   public void f()
   {
       if(foo.bar == bar) // foo.bar is visible here?!
       {
            //
       }
   }
}

有人对此有一个很好的解释吗?

Anyone has a good explanation about this?

推荐答案

访问修饰符在类级别起作用,而不在实例级别起作用级别:同一类中的所有代码都可以访问该类所有实例的私有成员。

Access modifiers work at the class level, not at the instance level: all code in the same class can access private members of all instances of the class.

对此没有什么特别奇怪的。

Nothing particularly strange about it.

这篇关于有参考资料时可以进行Java私有字段访问吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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