开发者

Why are private fields on an enum type visible to the containing class?

public class Parent {

    public enum ChildType {

        FIRST_CHILD("I am the first."),
        SECOND_CHILD("I am the second.");

        private String myChildStatement;

        ChildType(String myChildStatement) {
            this.myChildStatement = myChildStatement;
        }

        public String getMyChildStatement() {
            return this.myChildStatement;
        }
    }

    public static void main(String[] args) {

        // Why does th开发者_StackOverflowis work?
        System.out.println(Parent.ChildType.FIRST_CHILD.myChildStatement);
    }
}

Are there any additional rules with regard to access control for Parent subclasses, classes within the same package, etc., in reference to this enum? Where might I find those rules in the spec?


It has nothing to do with it being an enum - it has everything to do with private access from a containing type to a nested type.

From the Java language specification, section 6.6.1:

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.

For example, this is also valid:

public class Test {

    public static void main(String[] args) {
        Nested nested = new Nested();
        System.out.println(nested.x);
    }

    private static class Nested {
        private int x;
    }
}

Interestingly, C# works in a slightly different way - in C# a private member is only accessible within the program text of the type, including from any nested types. So the above Java code wouldn't work, but this would:

// C#, not Java!
public class Test
{
    private int x;

    public class Nested
    {
        public Nested(Test t)
        {
            // Access to outer private variable from nested type
            Console.WriteLine(t.x); 
        }
    }
}

... but if you just change Console.WriteLine to System.out.println, this does compile in Java. So Java is basically a bit more lax with private members than C# is.


Because the enum is effectively an inner class of the parent.


A top level class is like a village, everybody knows everybody, there are no secrets. Nested units within it don't change that fact.

class A
    private a;

    class B
        private b

        a = x; // ok

    new B().b = y; // ok

    class C extends A{}

    new C().a = z; // ok
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜