aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes interface implementation --- doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "interface implementation --- doubt" Watch "interface implementation --- doubt" New topic
Author

interface implementation --- doubt

Fred Close
Ranch Hand

Joined: Mar 13, 2001
Posts: 42

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

Joined: Feb 23, 2001
Posts: 104
Hi,
What you have here is annonymous class implementing Runnable.
Look at any resources about inner and annonymous classes.
Fred Close
Ranch Hand

Joined: Mar 13, 2001
Posts: 42

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

Joined: Jan 09, 2001
Posts: 1492
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.
 
 
subject: interface implementation --- doubt