-1

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(){});
Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
  • 3
    In your question you mean "instance", not "reference". Using the right vocabulary is very important if you want people to understand you. Otherwise your question has no meaning because you can create a reference to anything, class/abstract class/interface – Thibault D. Sep 28 '13 at 10:52

2 Answers2

3

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
   }
});
Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
1

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(){
    }
});
Community
  • 1
  • 1
Steve Benett
  • 12,843
  • 7
  • 59
  • 79
  • "Because an instance is created but no reference." - not true. What is it that the Thread constructor gets passed, if not a reference to a Runnable? – Ingo Sep 28 '13 at 11:35
  • @Ingo Yeah, right. Maybe my explanation is flawed in that point. The constructor will get a reference but there is no reference you can use after that. I still struggle by explaining things like this. – Steve Benett Sep 28 '13 at 11:40