在Java中,内部类(Inner Class)是定义在另一个类(外部类)内部的类。内部类可以访问外部类的所有成员(包括私有成员),并且可以访问外部类的实例变量和方法。根据访问权限和用途,Java提供了四种类型的内部类:成员内部类、局部内部类、匿名内部类和静态内部类。
public class OuterClass {
private int outerData = 10;
// 成员内部类
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;
// 局部内部类
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;
// 静态内部类
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
}
}