在Java中,內部類(Inner Class)是定義在另一個類(外部類)內部的類。內部類可以訪問外部類的成員(包括私有成員),而外部類也可以訪問內部類的成員。內部類可以分為四種類型:成員內部類、局部內部類、匿名內部類和靜態內部類。
public class OuterClass {
private int outerVar;
public class InnerClass {
public void accessOuterMembers() {
System.out.println("Accessing outer class variable: " + outerVar);
}
}
}
public class OuterClass {
public void createLocalInnerClass() {
final int localVar = 10;
class LocalInnerClass {
public void accessLocalVar() {
System.out.println("Accessing local variable: " + localVar);
}
}
LocalInnerClass localInner = new LocalInnerClass();
localInner.accessLocalVar();
}
}
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();
}
}
public class OuterClass {
private static int outerStaticVar;
public static class StaticInnerClass {
public void accessOuterStaticVar() {
System.out.println("Accessing outer static variable: " + outerStaticVar);
}
}
}