Java private field access possible when having a r

2020-02-12 04:13发布

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?

7条回答
倾城 Initia
2楼-- · 2020-02-12 05:07

It makes sense if you consider the intention of the 'private' modifier to hide implementation details.

Try thinking of it in terms of "this should be private to this class" (which in Java equates to "this should be private to this source file") rather than "this should be private to this instance".

查看更多
登录 后发表回答