在 Java 中,内部类(Inner Class)可以访问其外部类的所有成员,包括私有成员。内部类分为四种类型:成员内部类、局部内部类、匿名内部类和静态内部类。下面是各种内部类访问成员的方式:
public class OuterClass {
private int outerData = 10;
class InnerClass {
void display() {
System.out.println("outerData: " + outerData);
}
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display(); // 输出:outerData: 10
}
}
public class OuterClass {
public void createLocalInnerClass() {
final int localData = 20;
class LocalInnerClass {
void display() {
System.out.println("localData: " + localData);
}
}
LocalInnerClass localInner = new LocalInnerClass();
localInner.display(); // 输出: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 = 100;
private int outerData = 200;
static class StaticInnerClass {
void displayOuterStaticData() {
System.out.println("outerStaticData: " + outerStaticData);
}
void displayOuterData(OuterClass outer) {
System.out.println("outerData: " + outer.outerData);
}
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.StaticInnerClass staticInner = new OuterClass.StaticInnerClass();
staticInner.displayOuterStaticData(); // 输出:outerStaticData: 100
staticInner.displayOuterData(outer); // 输出:outerData: 200
}
}