2015-06-28 42 views
15

我怎么会叫从java.util.Random一个Randomsupertype constructor使用随机量和超

例如

Random rand = new Random(); 
int randomValue = rand.nextInt(10) + 5; 

public Something() 
{ 
    super(randomValue); 
    //Other Things 
} 

当我尝试这个编译器说,我“不能引用randomValuesupertype constructor之前一直被称为”。

回答

14

super()调用必须在构造函数中的第一个电话,并初始化实例变量的任何表达式将只有超级调用返回后进行评估。因此super(randomValue)尝试将尚未声明的变量的值传递给超类的构造函数。

一个可能的解决方案是让rand静态的(是有意义的有你的类的所有实例的单个随机数生成器),并生成构造函数中的随机数:

static Random rand = new Random(); 

public Something() 
{ 
    super(rand.nextInt(10) + 5); 
    //Over Things 
} 
+4

答案不是线程安全的。 –

+0

@SiyuanRen请原谅我,但是线程安全是什么意思? – Dan

+1

@Dan:这意味着从不同线程同时构造'Something'会导致微妙的错误。 beresfordt的答案没有这个问题。 –

7

另一种可能的解决方案是添加构造函数参数并拥有工厂方法;

public class Something extends SomethingElse { 
    private Something(int arg) { 
     super(arg); 
    } 

    public static Something getSomething() { 
     return new Something(new Random().nextInt(10) + 5); 
    } 
} 
0

这还不是最完美的解决方案,但另一种解决方案是有2个构造函数和无场。

public class Something extends SomethingElse{ 
    public Something(){ 
     this(new Random()); 
    } 

    private Something(Random rand){ 
     super(rand.nextInt(10) + 5); 
     //Other Things 
    } 
}