简体   繁体   中英

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. 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. 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).

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 .

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. For instance:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM