下面是关于java类嵌套的问题以至于无法实例化怎么回事啊??
来源:百度知道 编辑:UC知道 时间:2024/05/26 10:20:57
public class Test {
class Runner implements Runnable {
public void run() {
int i=1;
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
System.out.println(i++);
}
}
public static void main(String[] args) {
Runner run1=new Runner();
Runner run2=new Runner();
Thread t1=new Thread(run1);
t1.start();
}
}
这时候的run1和run2都没法实例化,把Runner类拿到Test类外面就好了,怎么回事啊???
class Runner implements Runnable {
public void run() {
int i=1;
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
System.out.println(i++);
}
}
public static void main(String[] args) {
Runner run1=new Runner();
Runner run2=new Runner();
Thread t1=new Thread(run1);
t1.start();
}
}
这时候的run1和run2都没法实例化,把Runner类拿到Test类外面就好了,怎么回事啊???
你把class Runner 放到Test中,Runner是test的内部类,Runner run1=new Runner();肯定不行.
拿出来后就是单独的一个类了
你可以看看内部类的相关介绍,内部类常用来实现监听器,多继承等等
public class Test {
class Runner implements Runnable {
public void run() {
int i=1;
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
System.out.println(i++);
}
}
public static void main(String[] args) {
Runner run1=new Test().new Runner();
Runner run2=new Test().new Runner();
Thread t1=new Thread(run1);
t1.start();
}
}
去看看书吧,这基本的规则没记住