在Java中,内部类(Inner Class)是定义在另一个类(外部类)内部的类。内部类可以访问外部类的所有成员(包括私有成员),并且可以有不同的访问级别(如public、protected、默认和private)。内部类可以分为四种类型:成员内部类、局部内部类、匿名内部类和静态内部类。
public class OuterClass {
private int data = 10;
class InnerClass {
public void accessOuterMembers() {
System.out.println("Accessing outer class data: " + data);
}
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.accessOuterMembers(); // 输出:Accessing outer class data: 10
}
}
public class OuterClass {
public void createLocalInnerClass() {
final int data = 10;
class LocalInnerClass {
public void accessOuterMembers() {
System.out.println("Accessing outer class data: " + data);
}
}
LocalInnerClass localInner = new LocalInnerClass();
localInner.accessOuterMembers(); // 输出:Accessing outer class data: 10
}
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 data = 10;
static class StaticInnerClass {
public void accessOuterStaticMembers() {
System.out.println("Accessing outer class static data: " + data);
}
}
public static void main(String[] args) {
OuterClass.StaticInnerClass staticInner = new OuterClass.StaticInnerClass();
staticInner.accessOuterStaticMembers(); // 输出:Accessing outer class static data: 10
}
}