This code is pretty much what I want to do:
import java.util.Random;
public class TestClass {
protected int testVarA;
protected int testVarB;
public TestClass() {
Random r = new Random();
this(r.nextInt(),r.nextInt());
}
public TestClass(int testVarA, int testVarB) {
this.testVarA = startTestVarA;
this.testVarB = startTestVarB;
}
}
However, this doesn't compile, since the this() statement has to be at the beggining of the function. I could do something like
this((new Random()).getNextInt(),(new Random()).getNextInt())
But that feels very improper. What is the proper way of doing this?
I would create your Random object as a static final variable outside of any constructors, so that you can reference it in the first line of your no-arg constructor.
private static final Random r = new Random();
public TestClass() {
this(r.nextInt(),r.nextInt());
}
This way, you only need one Random object, and it's initialized before the constructor's first line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With