This code declares an anonymous class which implements MouseListner., and the instanciate it.
Note that the body of this inner class is declared in your code.
Regards,<br />Seb<br /> <br />SCJP 1.4
Joined: Jun 13, 2005
Thanks for the reply.I know its anonymous class but the new keyword along with interface name confuses me. Any way is this legal?? Runnable r = new Runnable(); r.run(); I read its legal. if so why cheers Rajesh
Originally posted by Rajesh Chandra: Thanks for the reply.I know its anonymous class but the new keyword along with interface name confuses me. Any way is this legal?? Runnable r = new Runnable(); r.run(); I read its legal. if so why cheers Rajesh
This is not legal. Did you try to compile it? Since Runnable is an interface, you cannot instantiate it. However, you CAN create instantiate an anonymous inner class that implements Runnable like this:
You should note that this code will compile and run. However, Runnable is designed to be used with the Thread class for multi-threaded programs. The problem is that the above code does not use Thread, so the call to r.run() is still running on the main thread. This is not the main point of your question, though, so I'll just let you look into threads more on your own to understand why this is not a good idea.
Your new MouseListener() was valid because it provided all the required methods in the following curly braces. All that rather complex syntax defined a class that implements MouseListener. The new Runnable(); examle is not because it does not provide the required methods.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Dec 06, 2001
p.s. If you are interested, here is a thread in this forum that discusses the problems with calling r.thread().
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com