Reputation: 4360
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?
Upvotes: 3
Views: 57
Reputation: 395
Besides the Random object, you did not define startTestVarA and startTestVarB.
Upvotes: 1
Reputation: 5995
You can use move you complex initialization logic to a separate method:
public TestClass() {
Random r = new Random();
init(r.nextInt(),r.nextInt());
}
public TestClass(int testVarA, int testVarB) {
init(testVarA, testVarB)
}
private void init(int testVarA, int testVarB) {
this.testVarA = startTestVarA;
this.testVarB = startTestVarB;
}
This is more generic solution than just having Random
as a field. Random
field works in this particular case since all of the instances of the class can share it without any side-effects, but if you wanted to have something which is not thread-safe as an initializer, this might become a problem. Not even talking about the static field not being eligible for garbage collection. EVER
Upvotes: 1
Reputation: 6580
maybe like this?
import java.util.Random;
public class TestClass {
protected int testVarA;
protected int testVarB;
private static Random r = new Random();
public TestClass() {
this(r.nextInt(),r.nextInt());
}
public TestClass(int testVarA, int testVarB) {
this.testVarA = testVarA;
this.testVarB = testVarB;
}
}
Upvotes: 0
Reputation: 178303
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.
Upvotes: 2