Java內部類的實現方法有以下幾種:
public class OuterClass {
private int outerVar;
public class InnerClass {
public void innerMethod() {
outerVar = 10; // 訪問外部類的成員變量
outerMethod(); // 訪問外部類的方法
}
}
public void outerMethod() {
// ...
}
}
public class OuterClass {
private static int outerVar;
public static class InnerClass {
public void innerMethod() {
outerVar = 10; // 訪問外部類的靜態成員變量
outerMethod(); // 訪問外部類的靜態方法
}
}
public static void outerMethod() {
// ...
}
}
public class OuterClass {
public void outerMethod() {
class InnerClass {
public void innerMethod() {
// ...
}
}
InnerClass inner = new InnerClass();
inner.innerMethod();
}
}
public class OuterClass {
public void outerMethod() {
Runnable runnable = new Runnable() {
@Override
public void run() {
// ...
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}