4

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.

Marconius
  • 683
  • 1
  • 5
  • 13
  • possible duplicate of [Why can clone set a private field on another object?](http://stackoverflow.com/questions/976243/why-can-clone-set-a-private-field-on-another-object) – Jon Skeet Jun 29 '13 at 20:20
  • possible duplicate of [In Java, what's the difference between public, default, protected, and private?](http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private) – Rohit Jain Jun 29 '13 at 20:20
  • Basically, don't assume that the rules of one language apply to another language. Instead, learn the rules of the language you're using. In this case, look at the what the Java Language Specification has to say about the meaning of `private`. – Jon Skeet Jun 29 '13 at 20:20
  • it's just like you cannot know your name, NetBeans is right –  Jun 29 '13 at 21:05
  • I'm curious about what your logic is. If you describe why you think this should be invalid, we can provide a better explanation. Also, doubt your own understanding before you blame an IDE or compiler. – lealand Jun 29 '13 at 21:38

1 Answers1

13

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.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • That makes sense! The linked page doesn't actually have the bit you added in [], but I suppose that's what they meant by "its own class". Thanks for the answer. – Marconius Jun 30 '13 at 00:23