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内部类的基本用法。根据需求,您可以使用不同类型的内部类(非静态内部类、静态内部类、匿名内部类和局部内部类)。