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