Java-Class method can see private parameter fields of the same class

I encounter rather strange behavior and am not sure if this is a Java problem or just something with Eclipse.

Take the following code:

class Foo { private String text; public void doStuff(Foo f) { System.out.println(f.text); } } 

The problem is why f.text is available? This is a private field, so by my logic it should not be, but it seems the IDE seems to be that way.

+4
source share
1 answer

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 .

+12
source

Source: https://habr.com/ru/post/1488892/


All Articles