在Java中,内部类(Inner Class)是定义在另一个类(外部类)内部的类。内部类可以访问外部类的所有成员(包括私有成员),并且可以有不同的访问级别(如public、protected、默认和private)。内部类可以分为四种类型:成员内部类、局部内部类、匿名内部类和静态内部类。
public class OuterClass {
private int outerData = 10;
class InnerClass {
public void accessOuterMembers() {
System.out.println("outerData: " + outerData);
}
}
}
public class OuterClass {
public void createLocalInnerClass() {
final int localData = 20;
class LocalInnerClass {
public void accessLocalData() {
System.out.println("localData: " + localData);
}
}
LocalInnerClass localInner = new LocalInnerClass();
localInner.accessLocalData();
}
}
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 outerStaticData = 100;
private int outerData = 200;
static class StaticInnerClass {
public void accessOuterStaticData() {
System.out.println("outerStaticData: " + outerStaticData);
}
public void accessOuterData() {
// 无法访问非静态成员
// System.out.println("outerData: " + outerData);
}
}
}