[英]How do I have two classes in different lines interact with each other in Java?
我是Java的新手,我正在制作基於文本的冒險游戲。 在我的游戲中,有多個房間,每個房間都有一系列物品。 我有一個叫做“門”的課,我希望房間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)。
有沒有辦法讓這項工作?
我知道這意味着它不能告訴一個類在定義該類之前做某事,但我不知道如何修復它。
創建房間后,您需要添加項目。 這意味着您需要在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});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.