Peter is a DZone MVB and is not an employee of DZone and has posted 161 posts at DZone. You can read more from them at their website. View Full User Profile

Where Private Variables Can Be Shared Between Classes

  • submit to reddit
I have used nested classes which accessed the private members of top level classes for some time, and discovered that a top level class can access the private members of nested classes. Recently, I discovered that nested classes can access private member or other nested classes. i.e. where the two classes are not nested, but share a top level class.


Perhaps private should be called "file local" c.f. package local. ;)
public interface MyApp {
    class Runner {
        public static void main(String... args) {
            // access a private member of another class
            // in the same file, but not nested.
            SomeEnum.VALUE1.value = "Hello World"; 

    enum SomeEnum {
        private String value;

        SomeEnum(final String value) {
            this.value = value;
        public String toString() {
            return value;



Published at DZone with permission of Peter Lawrey, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)



Wojciech Kudla replied on Wed, 2012/03/07 - 3:22pm

There is no magic here. It's not that surprising when you read the spec

Peter Lawrey replied on Fri, 2012/12/21 - 4:34pm in response to: Wojciech Kudla

 There is some magic, given that the JVM doesn't support accessing private member from another class, nested or otherwise. The compiler creates accessor methods to implement this functionality.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.