我是一名学生。刚刚收到一份家庭作业,指出我应该调用构造函数方法而不是重用相同的代码。我复制了代码,因为我无法在没有错误的情况下调用构造函数。从单独的方法调用构造函数方法的正确语法是什么?
我确实进行了搜索,但找不到这个特定的(在类(class)内)问题。我确实尝试过使用“this”并创建一个类实例,但我不断收到错误。
import java.util.Random;
public class Coin {
// variable for a generic coin toss
private String sideUp;
// Constructor
// ******************** Instructor notes...
// This is the same code as your toss() method
// It is OK to call that method from your constructor.
// Don't copy/paste code or repeat yourself if not required.
public Coin() {
Random rand1 = new Random();
int x = rand1.nextInt(2);
if (x > 0){
sideUp = "Heads";
}else{
sideUp = "Tails";
}
}
//Void Method
public void toss() {
// how to call the Coin constructor above??????????????????????????
Coin();
}
}
最佳答案
反之亦然。将代码移回 toss 方法,然后从构造函数内部调用 toss()
。
import java.util.Random;
public class Coin {
// variable for a generic coin toss
private String sideUp;
// Constructor
// ******************** Instructor notes...
// This is the same code as your toss() method
// It is OK to call that method from your constructor.
// Don't copy/paste code or repeat yourself if not required.
public Coin() {
toss();
}
//Void Method
public final void toss() {
Random rand1 = new Random();
int x = rand1.nextInt(2);
if (x > 0){
sideUp = "Heads";
}else{
sideUp = "Tails";
}
}
}
正如其他评论和答案中指出的那样,调用可能从构造函数重写的方法是一个坏主意。这里有一个很好的解释:Why is it considered bad practice to call a method from within a constructor?
您可以像我在这里所做的那样将该方法设置为final
以避免出现问题。
关于java - 如何在另一个方法中调用类内的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22078231/