繁体   English   中英

为什么我要将私有构造函数与静态嵌套类组合在一起?

[英]Why would I combine a private constructor with a static nested class?

我正在挖掘Java类的可访问性。 虽然定义类有多种可能性,但我想知道下面示例的用例。

基本上, AnotherClass的构造AnotherClass是私有的。 但是, AnotherClass有一个静态嵌套类 ,可以在PublicClass类中访问。

这只是我出于好奇而想出来的东西,但是因为它实际上有效,我想知道,为什么我会使用这样的东西?

public class PublicClass {  
    public PublicClass() {
        AnotherClass.AnotherInnerClass innerClass = new AnotherClass.AnotherInnerClass();
        innerClass.anotherTest();
    }
}


class AnotherClass{
    /**
     * Private constructor - class cannot be instantiated within PublicClass.
     */
    private AnotherClass(){

    }

    /**
     * Static inner class - can still be accessed within package.
     */
    static class AnotherInnerClass{
        public void anotherTest(){
            System.out.println("Called another test.");
        }
    }
}

请注意,这些类在同一个文件中。

产量

Called another test.

AnotherInnerClass使用AnotherInnerClass的私有构造AnotherClass 例如,在Builder模式中使用它 ,这是这样的:

public class Foo {  
    public Foo() {
        Bar.Builder barBuilder = new Bar.Builder();
        Bar bar = barBuilder.build();
    }
}


public class Bar{
    private Bar(..){

    }

    static class Builder{
        public Bar build(){
            return new Bar(..);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM