“嗨,阿米戈!”

“嗨,艾莉!”

“今天我们有一个很有意思的话题,今天我要给大家讲讲嵌套类。”

“如果一个类声明在另一个类内部,那么它就是一个嵌套类。非静态嵌套类称为内部类。”

“内部类的对象嵌套在外部类的对象中,因此可以访问外部类的变量。”

例子
public class Car
{
 int height = 160;
 ArrayList doors = new ArrayList();

 public Car
 {
  doors.add(new Door());
  doors.add(new Door());
  doors.add(new Door());
  doors.add(new Door());
 }

class Door()
 {
  public int getDoorHeight()
  {
   return (int)(height * 0.80);
  }
 }
}

“注意 Door 类有一个 getDoorHeight 方法。它使用 Car 对象的高度变量并返回门的高度。”

嵌套类 - 1

“Door 对象不能独立于 Car 对象而存在。毕竟,它使用 Car 对象的变量。编译器在构造函数和 Door 类中无形地添加了对外部 Car 对象的引用,因此内部 Door 类的方法可以访问外部 Car 类的变量并调用其方法。”

“嵌套对象。对我来说很有意义。从图表来看,一切都非常简单。”

“就是这样。除了一些细微差别。”

“内部 Door 类引用了 Car 对象,因此:”

1) 不能在 Car 类的静态方法中创建 Door 对象,因为静态方法不包含对隐式传递给 Door 构造函数的 Car 对象的引用。

正确的 不正确
public class Car
{
 public static Door createDoor()
 {
  Car car = new Car();
  return car.new Door();
 }

 public class Door
 {
  int width, height;
 }
}
public class Car
{
 public static Door createDoor()
 {
  return new Door();
 }

 public class Door
 {
  int width, height;
 }
}

2) Door 类不能包含静态变量或方法。

正确的 不正确
public class Car
{
 public int count;
 public int getCount()
 {
  return count;
 }

 public class Door
 {
  int width, height;
 }
}
public class Car
{

 public class Door
 {
  public static int count;
  int width, height;

  public static int getCount()
  {
   return count;
  }
 }
}

“如果我需要一个由所有 Door 对象共享的变量怎么办?”

“你总是可以简单地在 Car 类中声明它。然后它将被嵌套在 Car 对象中的所有 Door 对象共享。”

3)注意:如果内部类声明为public,则可以在外部类之外创建它的实例,但必须先存在外部类的实例:

Car car = new Car();
Car.Door door = car.new Door();
Car.Door door = new Car().newDoor();

4)还有一条我差点忘了的评论。

“由于我们有两个嵌套对象,内部对象的方法可以访问两个名为‘this’的引用:”

public class Car
{
 int width, height;

 public class Door
 {
  int width, height;

  public void setHeight(int height)
  {
   this.height = height;
  }

 public int getHeight()
 {
  if (height != 0)
   return this.height;
  else
   return (int)(Car.this.height * 0.8);
 }
}

“我故意在类中声明了同名变量。”

“要在隐藏时从外部类访问变量,或在内部类中访问‘this’,只需编写‘YourClassName.this’:”

如何访问外部(或任何其他)类的“this”
Car.this
Car.Door.this
Car.Door.InnerClass2.InnerClass3.this

“所以,如果我们在内部类的方法中写‘this’,那么‘this’指的是内部类?”

“对,就是这样。”

“你觉得内部类怎么样,阿米戈?”

“它们非常有趣。我不会说它们太难了。”

“有很多限制,但在你解释了这些限制的来源和存在原因后,它们似乎很合乎逻辑。”

“另外,我已经在任务中编写嵌套类两个月了,但直到现在我才意识到我真正在写什么。”

“谢谢你的伟大教训,艾莉。”

“我很高兴你喜欢它,阿米戈。”