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

前端 未结 3 1100
清酒与你
清酒与你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题