使用randoms和super

Dan*_*Dan 15 java random compilation super

我怎么会叫一个Randomjava.util.Randomsupertype 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)

  • 根据它的javadoc`Rubom`是线程安全的,但随着警告`并发使用相同的Random实例跨线程可能会遇到争用和随之而来的糟糕性能.请考虑在多线程设计中使用ThreadLocalRandom (4认同)

ber*_*rdt 7

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

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)