我正在挖掘一点点到Java类的可访问性。尽管define classes有很多可能性,但我想知道下面的例子的用例。为什么我要将私有构造函数与静态嵌套类结合起来?
基本上,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.
*为什么我会永远使用这样的*这是丑陋的。只因为你**可以**写点什么,并不代表你应该***。 –
是的,我同意。我只是想知道是否有任何用例 - 就像你在一个严肃的项目中遇到过这样的代码一样?_ – mcuenez
请参阅下面的答案。我目前在一个用例中使用它,在这个用例中我的'Bar'被传递了很多,因为它的参数不能在一个类中设置。通过传递构造器而不是对象本身,我可以检查是否所有参数都是在调用'Builder.build()'函数时设置的,所以我确信所有设置都是正确的。 –