Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm encountering a rather odd behavior, and not sure if this is a Java issue 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 here is, why is f.text accessible? It's a private field, so by my logic, it shouldn't be, but the IDE seems to think it is.

like image 426
Marconius Avatar asked Dec 11 '22 13:12

Marconius


1 Answers

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.

like image 140
nanofarad Avatar answered Jan 31 '23 07:01

nanofarad