Dan*_*Dan 15 java random compilation super
我怎么会叫一个Random从java.util.Random成supertype constructor?
例如
Random rand = new Random();
int randomValue = rand.nextInt(10) + 5;
public Something()
{
super(randomValue);
//Other Things
}
Run Code Online (Sandbox Code Playgroud)
当我尝试这个时,编译器说我" 在调用randomValue之前无法引用supertype constructor".
Era*_*ran 14
该super()调用必须在构造函数中的第一个电话,并初始化实例变量的任何表达式将只有超级调用返回后进行评估.因此,super(randomValue)尝试将尚未声明的变量的值传递给超类的构造函数.
一种可能的解决方案是使rand静态(对于类的所有实例都有一个随机数生成器是有意义的)并在构造函数中生成随机数:
static Random rand = new Random();
public Something()
{
super(rand.nextInt(10) + 5);
//Over Things
}
Run Code Online (Sandbox Code Playgroud)
另一种可能的解决方案是添加构造函数参数并具有工厂方法;
public class Something extends SomethingElse {
private Something(int arg) {
super(arg);
}
public static Something getSomething() {
return new Something(new Random().nextInt(10) + 5);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
786 次 |
| 最近记录: |