java - 如何通过引用让一个Animal对象知道它在哪个Room

标签 java oop reference

我正在使用两个独立的类,AnimalRoomRoom 是用一个数组实例化的。 Animal 对象随后被实例化并放置在 Room 中的数组中。我如何才能为 Animal 对象提供对它们所在的 Room 的引用,以便当我对它们调用 look() 方法时,它们可以返回他们所在房间的名称吗?

public static void main(String[] args) {

Room mainRoom = new Room("The Lobby");

Animal gizmo = new Animal("Gizmo");        
mainRoom.addAnimal(gizmo);

System.out.println(mainRoom.toString());

gizmo.look();
}

-

public class Room {

private String name;
private Animal[] animals;
private Room currentRoom;
int i = 0;


public Room(String name) {
setName(name);
animals = new Animal[10];
}

public String toString() {
String temp = new String();
temp += "\nThis room is " + name + ".\n\n";
temp += "In the lobby are the following animals: \n";
for (Animal s : animals) {
    temp += s.toString() + "\n";
}
return temp;
}

public void setName(String name) {
this.name = name;
}

public void addAnimal(Animal a) {
    if (i < 10) {
    if (animals[i] != null) {
    i++;
    addAnimal(a);
    } else {
    animals[i] = a;

    }
} else {
    System.out.println("Room full");
}
}

}

-

public class Animal {

private Room currentRoom;
private String name;

public Animal() {
}

public Animal(String name) {
setName(name);
}

public void setName(String name) {
this.name = name;
}

public String toString() {
return "\t" + name;
}

public void look() {
    System.out.println(name + " is currently in " + getCurrentRoom());
//getCurrentRoom().toString();
}

public Room getCurrentRoom() {
return this.currentRoom;
}

public void setCurrentRoom(Room currentRoom) {
this.currentRoom = currentRoom;
}
}

最佳答案

How can I give the Animal objects a reference to what Room they are placed into so when I call a look() method on them, they can return the name of the Room they are in?

您应该在 Animal 中设置房间:

Animal gizmo = new Animal("Gizmo");    
gizmo.setCurrentRoom(mainRoom);    // this would set mainRoom as the attribute of gizmo

在此处进一步说明您的代码:

public void look() {
    System.out.println(name + " is currently in " + getCurrentRoom());
    //getCurrentRoom().toString();
}

将获取上面代码设置的 currentRoom

关于java - 如何通过引用让一个Animal对象知道它在哪个Room,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46024537/

相关文章:

java - 原始数据吞吐量上的非阻塞 io 与阻塞 io

java - 什么是原始类型,为什么我们不应该使用它呢?

java - 如何将 String 转换为 java 中的现有标识符?

javascript - 拥抱或对抗 Node 缺乏类型安全的问题

PHP 面向对象的表单生成器

c - C有引用吗?

c++ - 将对非指针成员变量的引用作为指针返回可以吗?

c++ - 推导 LValue 引用类型

java - 如何在 android 中声明位图/可绘制对象

java - 接口(interface)内的内部类