Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Where Private Variables Can Be Shared Between Classes

DZone's Guide to

Where Private Variables Can Be Shared Between Classes

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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.

Example

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"; 
            System.out.println(SomeEnum.VALUE1);
        }
    }

    enum SomeEnum {
        VALUE1("value1"),
        VALUE2("value2"),
        VALUE3("value3");
        private String value;

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

 

From http://vanillajava.blogspot.com/2012/02/outer-class-local-access.html

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}