另一个对象内的引用对象实例

时间:2015-02-19 22:16:48

标签: java object instance

我在主类末尾有以下代码来初始化对象并启动程序:

HumanPlayer humanPlayer = new HumanPlayer(baseHold);
Controller controller = new Controller(new ComputerPlayer(), humanPlayer, new Dice(seed));
controller.start();

在我的Controller类中,有以下代码:

public class Controller
{
    int roller;
    public Controller(ComputerPlayer cpuPlayer, HumanPlayer userPlayer, Dice dice)
    {
    }
//....
}

我不确定上面要初始化什么,因为我已经尝试了一些东西,它仍然没有在下面的代码中找到我的对象骰子:

public void start()
{
    for (int count = 0; count < 5; count++)
    {
        roller = dice.roll();
        System.out.println("Die roll: " + roller);
    }
}

roll 是Dice类中的一种方法。 是否有一种特殊的方式让我告诉它在我的控制器对象中寻找骰子作为对象而不是我的控制器对象中的变量,或者我是否完全错了?

我希望能够在这里掷骰子5次。

错误:

Controller.java:39: error: cannot find symbol
                roller = dice.roll();
                         ^
symbol:   variable dice
location: class Controller    
1 error

2 个答案:

答案 0 :(得分:1)

您必须将dice声明为Controller的实例字段,如下所示:

public class Controller {
    private Dice dice;
    // rest of the class code
}

然后在构造函数中,您将执行:

public Controller(ComputerPlayer cpuPlayer, HumanPlayer userPlayer, Dice dice) {
    // some other code
    this.dice = dice;
}

然后,您可以在this.dice类中的其他方法中使用Controller

答案 1 :(得分:0)

HumanPlayer humanPlayer = new HumanPlayer(baseHold);
Controller controller = new Controller(new ComputerPlayer(), humanPlayer new Dice(seed));
controller.start();

humanPlayernew Dice(seed)

之间需要逗号
HumanPlayer humanPlayer = new HumanPlayer(baseHold);
Controller controller = new Controller(new ComputerPlayer(), humanPlayer, new Dice(seed));
controller.start();