在Java中,內(nèi)部類(Inner Class)是定義在另一個(gè)類(外部類)內(nèi)部的類。內(nèi)部類可以訪問(wèn)外部類的所有成員(包括私有成員),因此它們?cè)谀承┣闆r下非常有用。根據(jù)使用場(chǎng)景和需求,您可以選擇以下幾種類型的內(nèi)部類:
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();
}
}
根據(jù)您的需求和使用場(chǎng)景,可以選擇適當(dāng)?shù)膬?nèi)部類類型。