在 Java 中,内部类(Inner Class)是定义在另一个类的内部的类。根据内部类与外部类的关系,可以分为四种类型:成员内部类、局部内部类、匿名内部类和静态内部类。下面分别介绍这四种类型的定义方法。
public class OuterClass {
private int outerData = 0;
public class InnerClass {
public void accessOuterData() {
System.out.println("outerData = " + outerData);
}
}
}
public class OuterClass {
public void createLocalInnerClass() {
final int localData = 0;
class LocalInnerClass {
public void accessLocalData() {
System.out.println("localData = " + localData);
}
}
LocalInnerClass localInner = new LocalInnerClass();
localInner.accessLocalData();
}
}
new
,并紧接着给出类的构造函数和实现代码。例如:public class OuterClass {
public void createAnonymousInnerClass() {
new Object() {
public void printMessage() {
System.out.println("This is an anonymous inner class.");
}
}.printMessage();
}
}
static
关键字。例如:public class OuterClass {
private static int outerStaticData = 0;
public static class StaticInnerClass {
public void accessOuterStaticData() {
System.out.println("outerStaticData = " + outerStaticData);
}
}
}