我是Java的新手,我正在制作基于文本的冒险游戏.在我的游戏中,有多个房间,每个房间都有一系列物品.我有一个叫做"门"的课,我希望房间A有一扇通往B室的门,反之亦然.但是当我这样做时:
public room A = new room(new items[] {
new door(B)});
public room B = new room(new items[] {
new door(A)});
Run Code Online (Sandbox Code Playgroud)
我收到错误消息"Cannot reference a field before it is defined"(我正在使用Eclipse).
有没有办法让这项工作?
我知道这意味着它不能告诉一个类在定义该类之前做某事,但我不知道如何修复它.
创建房间后,您需要添加项目.这意味着你需要编写一个addItem方法room.
public room A = new room();
public room B = new room();
{ // this is the start of an "instance initializer"; it runs before any constructors (but after field initializers)
// if you have a constructor, you could choose to put this in the constructor instead; personal preference
A.addItem(new door(B));
B.addItem(new door(A));
}
Run Code Online (Sandbox Code Playgroud)