在Java中,内部类(Inner Class)是定义在另一个类(外部类)内部的类。内部类可以访问外部类的所有成员(包括私有成员),因此它们在某些情况下非常有用。根据使用场景和需求,您可以选择以下几种类型的内部类:
class OuterClass {
private int data = 10;
class InnerClass {
void display() {
System.out.println("Data from outer class: " + data);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
}
}
class OuterClass {
private static int data = 10;
static class InnerClass {
void display() {
System.out.println("Data from outer class: " + data);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass.InnerClass inner = new OuterClass.InnerClass();
inner.display();
}
}
class OuterClass {
void display() {
final int data = 10;
class InnerClass {
void display() {
System.out.println("Data from outer class: " + data);
}
}
OuterClass.InnerClass inner = new OuterClass.InnerClass();
inner.display();
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.display();
}
}
class OuterClass {
private int data = 10;
void display() {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Data from outer class: " + data);
}
};
new Thread(runnable).start();
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.display();
}
}
根据您的需求和使用场景,可以选择适当的内部类类型。