This is by design. Private fields are accessible within the same class, even if a different instance. See here for more details and an official statement from Oracle on this. Since doStuff
is a member of Foo
, any private fields of Foo
are accessible for it.
The private modifier specifies that the member can only be accessed in its own class [even from a different instance]. [emphasis mine]
Now, the following code example does not work due to text
's visibility modifier:
class Bar{
public int baz;
public void doMoreStuff(Foo f){
System.out.println(f.text);
}
}
since doMoreStuff is defined in Bar
, not Foo
.