在Java中,內(nèi)部類(Inner Class)是定義在另一個類(外部類)內(nèi)部的類。內(nèi)部類可以訪問外部類的所有成員(包括私有成員),并且可以訪問外部類的實例變量和方法。根據(jù)訪問權(quán)限和用途,Java提供了四種類型的內(nèi)部類:成員內(nèi)部類、局部內(nèi)部類、匿名內(nèi)部類和靜態(tài)內(nèi)部類。
public class OuterClass {
private int outerData = 10;
// 成員內(nèi)部類
class InnerClass {
public void accessOuterMembers() {
System.out.println("outerData: " + outerData);
}
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.accessOuterMembers(); // 輸出:outerData: 10
}
}
public class OuterClass {
public void createLocalInnerClass() {
final int localData = 20;
// 局部內(nèi)部類
class LocalInnerClass {
public void accessLocalData() {
System.out.println("localData: " + localData);
}
}
LocalInnerClass localInner = new LocalInnerClass();
localInner.accessLocalData(); // 輸出:localData: 20
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.createLocalInnerClass();
}
}
public class OuterClass {
public void createAnonymousInnerClass() {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Anonymous inner class running.");
}
};
new Thread(runnable).start(); // 輸出:Anonymous inner class running.
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.createAnonymousInnerClass();
}
}
public class OuterClass {
private static int outerStaticData = 30;
// 靜態(tài)內(nèi)部類
static class StaticInnerClass {
public void accessOuterStaticData() {
System.out.println("outerStaticData: " + outerStaticData);
}
}
public static void main(String[] args) {
OuterClass.StaticInnerClass staticInner = new OuterClass.StaticInnerClass();
staticInner.accessOuterStaticData(); // 輸出:outerStaticData: 30
}
}