通常,您不需要将类嵌套到称为内部类的其他类中,除非一个类负责的工作可以分块成小单元,在其父类之外永远不需要知道这些小单元。
听起来您想要研究的概念是组合。当一个对象持有对另一个对象的引用时。
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 的方法现在可以使用它的 Room 实例(称为 room101)的方法。您将需要考虑您的房间的结构,以及您希望如何在您的酒店类中表示它。一些用于存储其他对象集合的对象包括ArrayList 和HashMap。
编辑:
this 是一个相当难以理解的概念,在您了解类与该类的实例(对象)的比较之前。在我的示例 Hotel 类的构造函数中,我有一个 Room 类型的变量,名为 room101。在构造函数之外是一个相同类型和名称的实例字段。
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 可以在没有它的情况下调用它自己的方法,只要没有其他同名的冲突符号。 (与实例字段/局部变量相比,方法不会发生这种情况)
希望这有助于澄清一些事情!