Tony Stark Tony Stark - 2 months ago 8
Java Question

trying to create a inner class that implement Runnable interface, got error: non static variable can not be referred from a static context

I'm trying to come up with a inner class that implement Runnable interface, create and start a new thread in the main method.

However, IDE keeps telling me that

Error:


non static variable can not be referred from a static context


I'm not exactly sure why this is happening? Could someone please enlighten me? Thanks in advance for any help!

public class Test {

class MyClass implements Runnable {
@Override
public void run(){
System.out.println("hello");
}
}

public static void main(String[] args) {
Thread t = new Thread(new MyClass()); //error: non static variable can not be referred from a static context

}
}

Answer
public static void main(String[] args) {
Test test = new Test(); 
    Thread t = new Thread(test.new MyClass());         
    t.start(); 
}

You need use it this way .