File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

interface implementation --- doubt

Fred Close
Ranch Hand

Joined: Mar 13, 2001
Posts: 42

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(){
Thread t = new Thread(r);

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
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(){};
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:

I agree. Here's the link:
subject: interface implementation --- doubt
It's not a secret anymore!