构造函数的Java自定义可选值
这段代码正是我想要做的:构造函数的Java自定义可选值,java,constructor,Java,Constructor,这段代码正是我想要做的: 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
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;
}
}
但是,这不会编译,因为this()
语句必须位于函数的末尾。我可以做类似的事情
this((new Random()).getNextInt(),(new Random()).getNextInt())
但这感觉很不合适。这样做的正确方法是什么?我将创建
随机
对象作为任何构造函数外部的静态final
变量,以便您可以在无参数构造函数的第一行引用它
private static final Random r = new Random();
public TestClass() {
this(r.nextInt(),r.nextInt());
}
这样,您只需要一个随机
对象,它在构造函数的第一行之前初始化。可能是这样的吗
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;
}
}
您可以使用将复杂的初始化逻辑移动到单独的方法:
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;
}
这是一种比仅将
随机
作为字段更通用的解决方案Random
字段在这种特殊情况下工作,因为类的所有实例都可以共享它,而不会产生任何副作用,但是如果您想使用一些不安全的初始化器,这可能会成为一个问题。甚至没有提到静态字段不符合垃圾收集的条件。曾经除了随机对象之外,您没有定义StartTestAra和StartTestArb