在 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);
}
}
}