【发布时间】:2017-04-06 16:23:23
【问题描述】:
我正在使用 BlueJ 在 Java 中为一个学校项目编写游戏(在非常基础的层面上),并且我试图将一个包含大量信息的构造函数拆分为两个或三个单独的构造函数。在我进行更改之前的初始代码如下所示:
public class Game
//fields omitted..
{
public Game() //initialise game
{
createRooms();
}
private void createRooms() // initialise rooms and exists and set start room.
{
Room bedRoom, kitchen;
bedRoom = new Room("in the bedroom");
kitchen = new Room("in the kitchen");
bedRoom.setExit("north", kitchen);
kitchen.setExit("south", bedRoom);
player = new Player(kitchen);
}
//Now, I want to seperate the contructor initialising the exits from the rest.
//I do so, by copying this to a new constructor below the createRooms constructor:
//initial code omitted..
private void createRooms() // initialise rooms
{
Room bedRoom, kitchen;
bedRoom = new Room("in the bedroom");
kitchen = new Room("in the kitchen");
}
private void createExits() // initialise room exits and set start room.
{
Room bedRoom, kitchen;
bedRoom.setExit("north", kitchen);
kitchen.setExit("south", bedRoom);
player = new Player(kitchen);
}
}
编译时,我在新构造函数中收到错误消息:“变量bedRoom 可能尚未初始化”。我不明白,因为变量是在前面的构造函数中初始化的。这可以从上面提供的信息和代码中解决吗?提前致谢!
BR 新手。
【问题讨论】:
-
你的构造函数是一行。你怎么可能希望它更短?
-
每个函数都有一个独立的、完全不相关的变量。你想要类中的一个字段。
-
你甚至没有一个真正的有任何参数的构造函数。您希望它如何更短?
-
你的类中只有一个构造函数,其他的都是私有方法。
标签: java constructor bluej