[英]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.