使用随机数和超级

Using randoms and super

如何将 Randomjava.util.Random 调用为 supertype constructor

例如

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

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

当我尝试这个时,编译器说我 "cannot reference randomValue before supertype constructor has been called".

super()调用必须是构造函数中的第一个调用,任何初始化实例变量的表达式只会在超级调用returns之后计算。因此 super(randomValue) 尝试将尚未声明的变量的值传递给超级 class 的构造函数。

一个可能的解决方案是使 rand 静态(为 class 的所有实例使用一个随机数生成器是有意义的)并在构造函数中生成随机数:

static Random rand = new Random();

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

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

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

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

这不是最优雅的解决方案,但另一种解决方案是有 2 个构造函数但没有字段。

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

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