我正在使用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