java 报错 cannot be referenced from a static context
报错:cannot be referenced from a static context,报错代码如下
public class neicunxielou {
    public static void main(String[] args)  throws Exception {
        MyThread myThread1 = new MyThread();
        myThread1.run();
    }
    private  class MyThread extends Thread{
        public void run(){
            System.out.println("hello");
        }
    }
}原因如下
MyThread是一个非静态的内部类,只能被这个类的非静态方法访问。main方法是静态方法,使用该类创建对象时会出错。解决办法有两个:
- 将MyThread变为静态的内部类,即加上static;
- 将类移到外面定义。
修改代码如下
neicunxielou {
    main(String[] args)  Exception {
        MyThread myThread1 = MyThread();
        myThread1.run();
    }
    MyThread Thread{
        run(){
            System..println();
        }
    }
} 
             
             
             
             
            