代码如下:
package com.inner;
public class People {
public static void main(String[] args) {
People people = new People();
people.child.speak1();
}
Child child = new Child();
String name = "外嵌类";
public void speak() {
System.out.println(this); // com.inner.People@66d3c617
System.out.println(name + ": speak 方法被调用了...");
}
class Child {
// 内部类可以访问外嵌类中的成员变量
String name2 = People.this.name;
String name = "内部类";
public void speak1() {
System.out.println(this); // com.inner.People$Child@5e481248
System.out.println(name2); // 为什么是Null
System.out.println(People.this.name); // 外嵌类
System.out.println(name); // 内部类
System.out.println(name + ":speak1掉用了..."); // 内部类:speak1掉用了...
System.out.println("===speak()===");
speak(); // 在内部类方法中调用内部类中的方法
System.out.println("============");
// System.out.println("===this.speak()===");
// this.speak(); // 在内部类方法中调用内部类中的方法
// System.out.println("============");
}
public void speak() {
// 当内部类中的方法和外嵌类方法名相同时
// 通过类名.this.方法名调用外嵌类同名方法
// speak();
System.out.println(name + ":speak 掉用了..."); // 内部类:speak 掉用了...
People.this.speak(); // 外嵌类: speak 方法被调用了...
}
}
}