Reputation: 1619
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.
Upvotes: 1
Views: 849
Reputation: 732
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(..);
}
}
}
Upvotes: 3