1

I have had a look for an explanation but haven't been able to find one. Why does this code work? Specifically - why can the private members of an instance be accessed? As far as I know it only works when the instance is created in a method inside the original class.

public class MyClass {
    private int thing;

    public MyClass () {}

    public MyClass makeMe () {
        MyClass myClass = new MyClass();
        myClass.thing = 1;
        return myClass;
    } 
}
bozzle
  • 1,106
  • 9
  • 9
  • 2
    Why do you think it *shouldn't* work? After all, this is in an instance method of that class. – Thorn G May 15 '15 at 02:20
  • 4
    *As far as I know it only works when the instance is created in a method inside the original class* So isn't that exactly what you are doing? – kaykay May 15 '15 at 02:21
  • 1
    Doesn't matter where the instance was created. Instances don't keep track of that. It is all about where the line of code is that tries to access your `thing` (and here that is in a method inside the original class, so it's all good). – Thilo May 15 '15 at 02:26
  • Thanks for your patience guys. Guess I was confused about private access. @Thilo - great explanation. – bozzle May 15 '15 at 03:28

2 Answers2

6

A private field can only be accessed by that class. You're still operating inside an instance of MyClass, so the private field is visible and accessible to you without the use of a setter.

To be a bit more formal... JLS 6.6.1 talks about access.

Here's the abridged snippet, emphasis mine:

  • A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:

    • ...Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
Community
  • 1
  • 1
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • Thanks Makoto - I appreciate that I could eventually have found that by RTFM. Much obliged :) – bozzle May 15 '15 at 03:32
2
public MyClass makeMe () {
    MyClass myClass = new MyClass();
    myClass.thing = 1;
    return myClass;
} 

is inside of the MyClass class, so it's able to access private members.

John Hodge
  • 1,645
  • 1
  • 13
  • 13