【发布时间】:2014-02-27 19:16:48
【问题描述】:
我是学生。刚拿回一个家庭作业,说明我应该调用构造函数方法而不是重用相同的代码。我复制了代码,因为我无法在没有错误的情况下调用构造函数。从单独的方法调用构造函数方法的正确语法是什么?
我确实进行了搜索,但找不到这个特定的(在课堂上)问题。我确实尝试过使用“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();
}
}
【问题讨论】:
-
硬币 newCoin = new Coin();
-
反过来做。将代码移回您的 toss 方法,然后从构造函数内部调用
toss()。 -
@MikeB 坏主意。您不应该从构造函数中调用该方法。请参阅我的答案以了解原因。
-
@RohitJain 所以让方法最终化。
-
谢谢,Arnaud,成功了!!
标签: java class methods constructor