*
The moose likes Beginning Java and the fly likes interface implementation and inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "interface implementation and inner classes" Watch "interface implementation and inner classes" New topic
Author

interface implementation and inner classes

Larry Frissell
Ranch Hand

Joined: May 16, 2008
Posts: 82
    
    2
I have see two implementations of a MouseListener interface and I am a little confused. In the first one I add "implements" to the class and implement the methods.



In the second example (shown below) uses an inner class to implement the MouseListener. Both examples seem to work fine, but I am confused by the use of "new MouseListener()", since it is an interface, not a class.

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19761
    
  20

Search for "anonymous classes".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39834
    
  28
I much prefer the second solution, which Rob has told you is called an anonymous class. You can see all sorts of examples where the parent Component implements an interface and the fooPerformed(FooListener f) method is full ofIf you add Listener objects to the individual Components, you can get direct communication between related objects.
Larry Frissell
Ranch Hand

Joined: May 16, 2008
Posts: 82
    
    2
Thank you Rob and Campbell, the clues help me find this article on using the anonymous classes to implement interfaces.
Brian Lang
Ranch Hand

Joined: Oct 21, 2008
Posts: 43
Larry, I just happened to ask this same question a week or so ago here:

http://www.coderanch.com/t/416796/java/java/Event-handling-Implementing-ActionListener-vs

Hope that's useful.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39834
    
  28
You're welcome. Those last two posts are exactly what we want to see; you give people a hint and they go and find out more information for themselves.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: interface implementation and inner classes