我收到了一项类(class)作业,其中我必须根据规范构建一个原型(prototype)酒店预订系统,如下所示:
You will need at least three classes:
Hotel
This should store all the essential information about a hotel, including a name and some rooms.
Room
This should store the number of beds in a room.
Bed
This should store the size of a bed (i.e. single or double).
我完全不知道从哪里开始!
我的印象是对象不能包含在其他对象中。
例如,假设我们实例化一个“Hotel”对象。然后我们如何实例化“Room”对象以及该对象内的“Bed”对象? 这些对象是如何存储的?我们如何从另一个对象间接与它们交互?
最佳答案
通常,您不需要将类嵌套到其他类(称为内部类)中,除非类负责的工作可以分成小单元,而这些单元永远不需要在其父类之外被了解。
听起来您想要研究的概念是“组合”。这是当一个对象持有另一个对象的引用时。
public class Room {
private boolean isVacant;
public Room() {
isVacant = true; // The room starts vacant
}
// Pretend there is a way for clients to check in and out of the room
public boolean isVacant() {
return isVacant;
}
}
public class Hotel {
// Using composition, I can make an instance of one class
// available to the methods of another
private Room room101;
public Hotel(Room room101) {
this.room101 = room101;
}
public boolean isRoom101Vacant() {
return room101.isVacant();
}
}
我们的酒店可能只有一个房间,用处不大,但这个示例展示了如何将一个对象“组合”到另一个对象中。 Hotel
的方法现在可以使用其名为 room101 的 Room
实例的方法。您需要考虑您的房间的结构,以及您希望如何在酒店类别中表示它。用于存储其他对象集合的一些对象包括 ArrayList 和 HashMap。
编辑:
在您了解类与该类的实例(对象)之间的比较之前,this
是一个相当难以理解的概念。在我的示例 Hotel 类的构造函数中,我有一个名为 room101
的 Room 类型变量。构造函数之外是相同类型和名称的实例字段。
Java 将始终引用最近作用域的变量或引用。因此,如果我有一个名为 room101 的方法引用,我如何在实例级别引用构造函数外部声明的另一个方法引用?这就是 this
发挥作用的地方。
public class ThisExample {
// This is a separate variable at the instance level
// Lets call this global in the comments
private int a;
public ThisExample() {
// This is a separate variable in the method level,
// lets call this local in the comments
int a;
a = 5; // our local is now assigned 5
this.a = 10; // Our global is now assigned 10
this.a = a; // our global is now assigned to 5
a = this.a * 2; // our local is now assigned to 10
}
}
简而言之,this
指的是类的“this”实例。这是类的实例像从外部引用自身一样的一种方式。就像另一个对象将 room101
的方法引用为 room101.isVacant()
一样。 Room 类中的方法将类似地执行 this.isVacant()
以获得相同的效果。
最后一点,如果一个类中只有一个符号声明。 this
关键字是隐含的。因此,只要没有其他同名冲突符号,Room 也可以在没有它的情况下调用它自己的方法。 (这种情况在方法中不会像在实例字段/局部变量中那样发生)
希望这有助于澄清问题!
关于java - Java 中的对象内的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34125772/