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

前端 未结 3 1140
清酒与你
清酒与你 2021-02-20 12:44
public class Parent {

    public enum ChildType {

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

        private String myChild         


        
相关标签:
3条回答
  • 2021-02-20 12:52

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

    0 讨论(0)
  • 2021-02-20 13:04

    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 讨论(0)
  • 2021-02-20 13:15

    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.

    0 讨论(0)
提交回复
热议问题