我正在挖掘一點點到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()'函數時設置的,所以我確信所有設置都是正確的。 –