Forums Register Login
interface implementation --- doubt
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 ?
What you have here is annonymous class implementing Runnable.
Look at any resources about inner and annonymous classes.
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
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:


This thread has been viewed 553 times.

All times above are in ranch (not your local) time.
The current ranch time is
Dec 10, 2018 10:06:51.