我如何让不同行中的两个 类 在 Java 中相互交互?

How do I have two classes in different lines interact with each other in Java?

我是 Java 的新手,我正在制作一款基于文本的冒险游戏。在我的游戏中,有多个房间,每个房间都有一系列物品。我有一个名为 "door," 的 class,我希望房间 A 有一扇门通向房间 B,反之亦然。但是当我这样做时:

    public room A = new room(new items[] {
new door(B)});
    public room B = new room(new items[] {
new door(A)});

我收到 错误 消息 "Cannot reference a field before it is defined"(我使用的是 Eclipse)。

有没有办法让它工作?

我知道这意味着它无法告诉 class 在定义 class 之前做某事,但我不知道如何修复它。

您需要在创建房间后添加项目。这意味着您需要在 room.

中编写一个 addItem 方法
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));
}

A和B都初始化完成后需要设置A的项目。例如:

public room A = new room();
public room B = new room();
{
    B.setItems(new items[] {A});
    A.setItems(new items[] {B});
}