We can create a reference of an interface but not object. But how can we pass new Runnable() to the Thread constructor. As per as my knowledge is concert new Class_Name() is object.
Thread t = new Thread(new Runnable(){});
We can create a reference of an interface but not object. But how can we pass new Runnable() to the Thread constructor. As per as my knowledge is concert new Class_Name() is object.
Thread t = new Thread(new Runnable(){});
The trick used here is called anonymous classes. Basically, you are creating a object of a new anonymous class that implements Runnable
.
The better example would be this:
Thread t = new Thread(new Runnable(){
@Override
public void run() {
// Code here
}
});
We can create a reference of an interface but not object
That's not true.
ClassA classa = new ClassA();
This will make a new instance for ClassA, while classa
is the reference.
But how can we pass new Runnable() to the Thread constructor
Thread t = new Thread(new Runnable(){});
This will make an instance of a Thread, where t
is the reference. The new Runnable(){} is called an anonymous class. Because an instance is created, the reference is passed to the constructor, but you can't refer to this one later in the code.
But with this line you should get a compile error. You have to override the run method.
Thread t = new Thread(new Runnable(){
@Override
public void run(){
}
});