实例化内部类必须先实例化外部类,然后把内部类当做成员变量来实例化
public class TestThread {
public static void main(String[] args) {
TestThread t = new TestThread(); //先实例化外部类,把内部类当做成员变量实例化
Thread t1 = t.new PrintThread(1);//实例化内部类方式
Thread t2 = t.new PrintThread(2);
t1.start();
t2.start();
}
class PrintThread extends Thread{
private int threadNum;
public PrintThread(int threadNum) {
this.threadNum = threadNum;
}
public PrintThread() {
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("线程"+threadNum+"正在运行");
}
}
}
本文详细解析了Java中如何实例化内部类,通过具体代码示例展示了内部类的使用方式。强调了实例化内部类前需先实例化外部类,并将内部类作为成员变量进行实例化的关键步骤。
1436

被折叠的 条评论
为什么被折叠?



