Je suis en train de programmer un jeu (à un niveau très basique) pour un projet d'école en Java en utilisant BlueJ, et j'essaie de séparer un constructeur, contenant beaucoup d'informations, en deux ou trois constructeurs. Le code initial, avant mes changements se présente comme suit:Plusieurs constructeurs en 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);
}
}
Quand je compile, je reçois le message d'erreur dans le nouveau constructeur: « peut-être pas la variable BedRoom ont été initialisées ». Je ne comprends pas, puisque la variable a été initialisée dans le constructeur précédent. Cela peut-il être résolu à partir des informations et du code fournis ci-dessus? Merci d'avance!
BR Le débutant.
Votre constructeur est une ligne. Comment pouvez-vous vouloir qu'il soit plus court? –
Chacune de vos fonctions a une variable distincte, complètement indépendante. Vous voulez un champ dans la classe. – SLaks
Vous n'avez même pas un vrai constructeur qui a des paramètres. Comment voulez-vous que ce soit plus court? – Grunzwanzling