简体   繁体   English

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

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

I'm new to Java, and I'm making a text-based adventure game. 我是Java的新手,我正在制作基于文本的冒险游戏。 In my game, there are multiple rooms, and the rooms each hold an array of items. 在我的游戏中,有多个房间,每个房间都有一系列物品。 I have a class called "door," and I want room A to have a door leading to room B and vice versa. 我有一个叫做“门”的课,我希望房间A有一扇通往B室的门,反之亦然。 But when I do this: 但是当我这样做时:

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

I get the error message "Cannot reference a field before it is defined" (I'm using Eclipse). 我收到错误消息"Cannot reference a field before it is defined" (我正在使用Eclipse)。

Is there a way to make this work? 有没有办法让这项工作?

I know that that means it can't tell a class to do something before that class is defined, but I don't know how to fix it. 我知道这意味着它不能告诉一个类在定义该类之前做某事,但我不知道如何修复它。

You will need to add the items after you create the rooms. 创建房间后,您需要添加项目。 This means you'll need to write an addItem method in room . 这意味着您需要在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));
}

You need to set the items of A after both A and B have been initialized. 在初始化A和B之后,您需要设置A的项目。 For instance: 例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让数组互相交互? - How do I make arrays interact with each other? 如何将两个不同的对象相互关联 - How to do I associate two different objects with each other java中如何让对象相互交互? - How to make objects interact with each other in java? Java:如何在第三类中创建两个不同类的实例,并通过构造函数相互传递引用 - Java: how to create instances of two different classes in a third class and pass references to each other through the constructors 如何使两个不同的程序包访问彼此的类而又不允许任​​何其他第三个程序包在Java中访问它? - How to make two different packages access each other's classes without allowing any other third package to access it in java? 如何在JOGL中旋转彼此独立的两条线? - How do i rotate two lines independent of each other's axes in JOGL? 在java中的neo4j嵌入式数据库中,我应该如何检查两个节点是否相互关联? - How should I check if two nodes have relationship with each other,in neo4j embedded database in java? 如何创建一个新类来处理Java中的其他两个类? - How do I create a new class to process two other classes in Java? 如何使两个函数相互调用Java - How to have two functions that call each other Java 如何使用JUnit测试两个都具有Java主要方法的类(客户端和服务器)? - How do I use JUnit to test two classes (a client and a server) that both have main methods in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM