Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interface implementation --- doubt

 
Fred Close
Ranch Hand
Posts: 42
Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I've seen the following code in a book it's compiling but I don't understand why
Runnable r = new Runnable(){
public void run(){
Work.doIt();
}
};
Thread t = new Thread(r);
t.start();

what are we doing here creating a class that implements an interface(I assume so) but what's the type of the class ?
where can I find more information on this topic ?
 
raimondas zemaitis
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
What you have here is annonymous class implementing Runnable.
Look at any resources about inner and annonymous classes.
 
Fred Close
Ranch Hand
Posts: 42
Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought you created anonymous class this way :
new interface_name(){};
or
new class_name(){};
where interface name is the interface to implement and class_name the class to extend.
here you don't have a reference to the new class you create, I thought that's why you call them anonymous class
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Fred,
Yes, you are right! Raimondas is also correct.
Your anonymous interface is:

It is created just like you described. It is anonymous because it has no name associated with it (i.e., can't use constructor because name is missing!).
That is different from the reference variable that points to the anonymous interface! Just because we have a reference to an anonmyous interface doesn't change it from being anonymous!
The code above is short hand for creating a whole class that extends the Runnable interface just to override the run method.
The longhand:

Regards,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic