• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

interface implementation --- doubt  RSS feed

 
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 ?
 
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
 
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
Boost this thread!