为什么可以访问嵌套静态类的成员?

时间:2013-06-04 18:59:16

标签: java encapsulation static-members nested-class

我有一个名为Adjudicator的嵌套静态类(在我阅读有效Java中的Builder模式之前,我没有问过......我有点异想天开)这是一个构建器,即Client.Adjudicator构建Client对象

与Joshua Bloch在Effective Java中作为示例提供的构建器一样,它通过调用封闭类的构造函数来构建“封闭”类的对象(静态嵌套类不是真正封闭的)。我的班级看起来像这样:

public class Client extends DB {

    private IntegerProperty id =         new SimpleIntegerProperty();
    private LongProperty    defmrnKey =  new SimpleLongProperty();
    private StringProperty  lastName =   new SimpleStringProperty();
    private StringProperty  midName =    new SimpleStringProperty();
    private StringProperty  firstName =  new SimpleStringProperty();
    private IntegerProperty doB =        new SimpleIntegerProperty();
    private StringProperty  gender =     new SimpleStringProperty();

    :
    :

    Client(Client cli) {  // Copy constructor

        this.id.set(cli.getID());
        this.defmrnKey.set(cli.getDefMRNKey());
        this.lastName.set(cli.getLastName());
        this.midName.set(cli.getMidName());
        this.firstName.set(cli.getFirstName());
        this.doB.set(cli.getDoB()); 
        this.gender.set(cli.getGender());
    }

    Client(Client.Adjudicator ad) {  // Invoked by builder

        this.id.set(ad.m_id);
        this.defmrnKey.set(ad.m_defmrnkey);
        this.lastName.set(ad.m_ln);
        this.midName.set(ad.m_mn);
        this.firstName.set(ad.m_fn);
        this.doB.set(ad.m_dob); 
        this.gender.set(ad.m_gen);
    }

    :
    :

    public static class Adjudicator {


        private int     m_id               = DB.KEY_UNDEFINED;
        private long    m_defmrnkey        = DB.KEY_UNDEFINED;
        private String  m_ln               = null;
        private String  m_mn               = null;
        private String  m_fn               = null;
        private int     m_dob              = DB.KEY_UNDEFINED;
        private String  m_gen              = null;

        :
        :

        public Client build() {

            // Invariants all checked here; if ok then...

            return new Client(this);
        }
    }
}

从JVM的角度来看,静态嵌套类是一个顶级类,因此它的实例不依赖于任何Client实例。

然而,我的Client类能够自由访问其构建器类的私有成员......即使它们是私有的并且位于单独的顶级类中。

为什么这样做?这不会破坏封装吗?我很高兴这有效,但这对我来说并不直观。

1 个答案:

答案 0 :(得分:3)

  

从JVM的角度来看,静态嵌套类是顶级类

不完全像你发现的那样。私有成员的范围是顶级封闭类。在您的情况下,它是整个Client类。

请注意,它可以双向工作,您的Adjudicator课程也可以访问Client课程的私人成员。

参考:JLS #6.6.1

  

如果成员被声明为私有,那么当且仅当它发生在包含成员声明的顶级类的主体内时才允许访问

相关问题