简体   繁体   中英

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

I'm currently digging a little bit into accessibility of Java classes. While there is a varity of possibilities to define classes , I wonder about a use case for the example below.

Basically, the constructor of AnotherClass is private. However, AnotherClass has a static nested class , which is accessible within the PublicClass class.

It's just something I came up with out of curiosity, but as it actually works, I wonder, why would I ever use something like this?

Example

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.");
        }
    }
}

Note those classes are within the same file.

Output

Called another test.

The AnotherInnerClass CAN use the private constructor of AnotherClass . This is used for example in the Builder pattern , which is something along the lines of this:

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(..);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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