2014-03-30 92 views
-1

問題1:這個代碼是一個構造函數還是一個方法,或者它是什麼?
問題2:這個return語句是如何工作的(兩者)?
任何人都可以請解釋...靜態工廠方法查詢

public class RandomIntGenerator 
{ 
    private final int min; 
    private final int max; 

    private RandomIntGenerator(int min, int max) { 
     this.min = min; 
     this.max = max; 
    } 

    public static RandomIntGenerator between(int max, int min) //Prob 1  
    { 
     return new RandomIntGenerator(min, max);     //Prob 2  
    } 

    public static RandomIntGenerator biggerThan(int min) { 
     return new RandomIntGenerator(min, Integer.MAX_VALUE);  //Prob 2  
    } 

    public static RandomIntGenerator smallerThan(int max) { 
     return new RandomIntGenerator(Integer.MIN_VALUE, max); 
    } 

    public int next() {...}  //its just a method 
} 

回答

0

它們基本上是其返回RandomIntGenerator類的新實例的方法。一旦你有了這些,你可以使用next()方法來獲得隨機數字。

RandomIntGenerator generator = RandomIntGenerator.between(5, 10); 
int a = generator.next(); //a is now a "random" number between 5 and 10. 

如果構造函數是公共的,您可以用下面的代替第一行,因爲它們具有相同的效果。

RandomIntGenerator generator = new RandomIntGenerator(5, 10); 
+0

因此,這些被用來代替構造函數?它寫道,這是替代選項使用具有相同名稱和簽名的構造函數。 – user3436422

+0

那麼這將是一個替代選項,但是構造函數是私有的,所以你不能在'RandomIntGenerator'類之外訪問它。如果你願意,你可以擺脫這些方法,並將構造函數的'private'修飾符更改爲'public'。或者你可以擁有兩種,無論你喜歡什麼。 – Arrem

+0

不,它不能像靜態工廠方法一樣,我們使構造函數私有。如果我們想要聲明具有相同名稱和簽名的多個構造函數。它如何調用這個私有構造函數。 – user3436422