java - How is it that I am able to reference private fields of an instance inside a class? -


i have had explanation haven't been able find one. why code work? - why can private members of instance accessed? far know works when instance created in method inside original class.

public class myclass {     private int thing;      public myclass () {}      public myclass makeme () {         myclass myclass = new myclass();         myclass.thing = 1;         return myclass;     }  } 

a private field can accessed class. you're still operating inside instance of myclass, private field visible , accessible without use of setter.

to bit more formal... jls 6.6.1 talks access.

here's abridged snippet, emphasis mine:

  • a member (class, interface, field, or method) of reference (class, interface, or array) type or constructor of class type accessible if type accessible , member or constructor declared permit access:

    • ...otherwise, if member or constructor declared private, access permitted if , if occurs within body of top level class (§7.6) encloses declaration of member or constructor.

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -