Java內部類(Inner Class)是定義在另一個類(外部類)內部的類。使用Java內部類可以訪問外部類的所有成員(包括私有成員),并且可以創建外部類的實例。以下是Java內部類的一些常見用法:
public class OuterClass {
private int data = 10;
class InnerClass {
public void accessOuterMembers() {
System.out.println("Outer class data: " + data);
}
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.accessOuterMembers(); // 輸出:Outer class data: 10
}
}
public class OuterClass {
private int data = 10;
class InnerClass {
public void createOuterInstance() {
OuterClass outer = new OuterClass();
System.out.println("Outer class data: " + outer.data);
}
}
public static void main(String[] args) {
OuterClass.InnerClass inner = new OuterClass().new InnerClass();
inner.createOuterInstance(); // 輸出:Outer class data: 10
}
}
public class OuterClass {
private static int data = 10;
class InnerClass {
public void accessOuterStaticMembers() {
System.out.println("Outer class static data: " + OuterClass.data);
}
}
public static void main(String[] args) {
OuterClass.InnerClass inner = new OuterClass().new InnerClass();
inner.accessOuterStaticMembers(); // 輸出:Outer class static data: 10
}
}
public class OuterClass {
private int data = 10;
public void createInner() {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Outer class data: " + data);
}
};
new Thread(runnable).start();
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.createInner(); // 輸出:Outer class data: 10
}
}
public class OuterClass {
private int data = 10;
public void createLocalInner() {
class LocalInnerClass {
public void accessOuterMembers() {
System.out.println("Outer class data: " + data);
}
}
LocalInnerClass localInner = new LocalInnerClass();
localInner.accessOuterMembers(); // 輸出:Outer class data: 10
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.createLocalInner(); // 輸出:Outer class data: 10
}
}
這些示例展示了Java內部類的基本用法。根據需求,您可以使用不同類型的內部類(非靜態內部類、靜態內部類、匿名內部類和局部內部類)。