This is by design. Private fields are available within the same class, even if it is a different instance. See here for more details and an official Oracle statement on this subject. Since doStuff is a member of Foo , any private Foo fields are available to it.
A private modifier indicates that access to an element can only be accessed in its class [ even from another instance ]. [emphasis mine]
Now the following code does not work due to the text 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 .
source share