Java学习之No enclosing instance of type 的解决方法

上一篇 / 下一篇  2016-11-15 14:57:22 / 个人分类:Java学习

学习java多线程,自己写例子程序如下:
import java.util.*;
import java.lang.*;
public class TestJoin {
public static void main(String[] args){
Mythread1 thread = new Mythread1("sdfafmm");
thread.start();
try{
thread.join();
}catch(InterruptedException e){}
for(int i=0;i<=10;i++){
System.out.println("I am Thread1");
}

}
class Mythread1 extends Thread{
Mythread1(String s){
super(s);
}
public void run(){
for(int i=0;i<=10;i++){
System.out.println("my name is "+getName()+" "+getId());
try{
sleep(1000);
}catch(InterruptedException e){
return;
}
}
 }
}
}
编译执行时总是提示:No enclosing instance of type TestJoin is accessible. Must qualify the allocation with an enclosing instance of type TestJoin (e.g. x.new A() where x is an instance of TestJoin).提示没有可访问的内部类 TestJoin的实例,必须分配一个合适的内部类E的实例(如x.new A(),x必须是 TestJoin的实例。)可已经用new实例化了这个类,为什么还不行呢。
解决方法:Mythread1 类前面加public static,把该类修饰为静态类
出现原因:由于主程序中的main方法是静态方法,而Mythread1 类是动态类,java中类的静态方法无法调用动态类中的方法,只有把Mythread1修饰为静态类,这样才能调用静态类中方法和成员变量。


TAG: accessible allocation Java学习 where

 

评分:0

我来说两句

Open Toolbar