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