Search code examples
javaaccess-modifiersprivate-members

Java private field access possible when having a reference?


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?


Solution

  • 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.