加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么枚举类型上的私有字段对包含类可见?

发布时间:2020-12-14 05:32:52 所属栏目:Java 来源:网络整理
导读: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
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 this work?
        System.out.println(Parent.ChildType.FIRST_CHILD.myChildStatement);
    }
}

有关参与此枚举的父子类,相同包中的类等的访问控制有其他规则吗?我可以在规范中找到这些规则吗?

解决方法

它与枚举无关 – 它与从包含类型到嵌套类型的私有访问有关.

从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.

例如,这也是有效的:

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;
    }
}

有趣的是,C#的工作方式略有不同 – 在C#中,私有成员只能在类型的程序文本中访问,包括任何嵌套类型.所以上面的Java代码将不起作用,但是这样做会:

// 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); 
        }
    }
}

…但是如果您只是将Console.WriteLine更改为System.out.println,那么它将以Java编译.所以Java基本上比C#的私人成员更松懈.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读