我正在使用BlueJ编写一个Java学校项目的游戏(在一个非常基础的层面上),我试图将一个包含大量信息的构造函数分成两个或三个单独的构造函数。最初的代码,我改变之前如下所示: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);
}
}
当我编译,我得到了新的构造函数中的错误消息:“可变卧室可能没有被初始化”。我没有得到这个,因为变量是在前面的构造函数中初始化的。这可以从上面提供的信息和代码解决吗?提前致谢!
BR 新手。
您的构造函数是一行。你怎么可能希望它更短? –
你的每个函数都有一个单独的,完全不相关的变量。你想在课堂上有一个领域。 – SLaks
你甚至没有一个真正的构造函数,它有任何参数。你想如何缩短它? – Grunzwanzling