permaculture playing cards*
The moose likes Beginning Java and the fly likes Anynomous Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Anynomous" Watch "Anynomous" New topic


Muhammad Ahsan Jamshaid
Ranch Hand

Joined: Jun 01, 2006
Posts: 59
what's the reason to use Anonymous Inner Class and how to use them properly.......


--Ahsan Jamshaid... SCJP 5(80%)
marc weber

Joined: Aug 31, 2004
Posts: 11343

See Anonymous inner classes from Thinking in Java. (Be aware, however, that Eckel misuses the term "inner class" to mean "nested class," as defined in the JLS.)
[ August 31, 2006: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 38519
The commonest anonymous classes are Runnables and Listeners. Most people come across them first when adding action Listeners to Buttons in swing, so I shall talk about them first.

You will find

in some books, and passim in the Java Tutorial. I look on that as an abomination against object-orientated programming. What happens is that you end up with an actionPerformed() method full of if else like this:-You end up with the same class which displays your window (a JFrame, which in the MVC = model-view-control class should be "V" for view), having a great big actionPerformed method. Imagine how awkward it would be to add a blue button to that method, or even worse, to remove the red button and replace it with a blue button. So, most of the time, I avoid addActionListener(this) like the plaque, and suggest you do so too.

There is one instance, however where addSomethingListener(this) is actually useful, which is when the event actually affects the view. You know those little boxes you get on some drawing applications which show the location of the mouse in pixels? That is done with a mouseMotionListener; you put something like this as its mouseMoved method (and you need an empty mouseDragged method for this example).You can also have WindowListeners, which have to be added to the JFrame, which react when the window changes size. Again this refers directly to a Swing component, so addWindowListener(this) is appropriate.

That leaves two other possibilities for implementing Listeners.
  • An anonymous class.
  • An ordinary class.

  • If you have several components which do the same thing, or similar things, go for an ordinary class. ActionListener is an interface and it has one method, so you have to get a class which implements that interface and implements its method.
    [The MouseMotionListener I quoted earlier has two methods.]
    I usually give the example of Listeners for changing colours: You can have several buttons which do similar things.[You can tell from the spellings that I am British.]
    Think how easy it would be to add a blueButton now. And if you say. . . you can have two objects which use the same Listener.

    BTW: the "myComponent" has to be either a field or a final local variable.

    You can put that ColourListener in a class of its own as a public class, or as a private class inside the display class, or even inside a method. If inside the other class you call in a private inner class. You can also have protected or default access inner classes, but not public.
    If it is a public class, you might have to pass "myComponent" to it as a constructor argument as well.

    You can run almost all Listeners quite adequately using private inner classes like that, and a few things with "this," like the mouseMoved example I gave earlier. You can actually get away with never using an anonymous inner class, but I think they are useful in certain circumstances, because you have all the coding in the same place.

    Use an anonymous inner class if you have one component which does one thing and none of the other components does anything similar. Don't copy what is in the books. Write it like this (unless you use an IDE, in which case you let it find an error and sort it out for itself!). Remember it won't compile in the earlier stages.

    1: imports. Most of the classes and interfaces you need live in java.awt.event.

    2: When you add a Button (it works with buttons, menu items, radio buttons, check boxes, etc), add the Listener. For such components, use an ActionListener rather than the "lower level" listeners like MouseListener.

    3: Break the line. Put your cursor inside the () and push "enter" twice.

    4: Put something inside the space in the (), namely the heading for the class, "new ActionListener()" with () to show it is a constructor call. No semicolon this time.5: Add the {} for the class body, after the ().6: Implement the method required. If you look up ActionListener in the API you will find only one method.
    At this point your class will compile, but nothing will happen.

    7: Put something useful inside the action performed method. Try to keep it short. Very short. A method call is a good idea.Remember "myData" must be a field or a "final" local variable. The compiler will tell you off if you use an ordinary local variable. And make sure your method signature is spelt exactly the way it says in the API.

    Another example, using a Runnable:-

    Some people don't like anonymous classes, but I do. I hope i haven't confused you too much. CR
    Muhammad Ahsan Jamshaid
    Ranch Hand

    Joined: Jun 01, 2006
    Posts: 59
    Thanks for help.
    How to use them is Clear but i am struggling with where and why to use them. Please help it out in more simpler way.

    Muhammad Ahsan Jamshaid
    Ranch Hand

    Joined: Jun 01, 2006
    Posts: 59
    public class A{

    public A(){...}

    public void doA(){ //... something.. }

    }// A ends..

    Here is another calss B

    public class B{
    public A a ;

    public B(){...}

    public static void main (String arg[]){

    B b = new B();
    b.a = new A(){

    //lines of discussion

    public void doA(){ //... another implimentation.. }


    }// end main
    }end B

    What is this? is ther some concept of anonymous class involved here?

    Campbell Ritchie

    Joined: Oct 13, 2005
    Posts: 38519
    s ther some concept of anonymous class involved here?
    Not that I can see. Your classes have names, even though they are too short to use in real life (A or B). A class like "new ActionListener" hasn't got a name.

    Did anybody who is not a beginner notice the mistake I made in my earlier posting?
    I wrote "save(this);" which should have read "save(OuterClass.this);" Otherwise you end up saving the details of the Listener.
    Also I wrote "mouseLocationPanel.setText()". It is a bit unlikely that a panel would have text, more likely it would be a label or text area.

    Please help it out in more simpler way.
    There isn't a simpler way. Find examples in the books (unfortunately you might have a long search to find them in the Java Tutorial). Copy them. But don't copy the anonymous classes line by line, write them out the way I showed you earlier. It is not easy remembering such classes. That is why you buy books with examples in, and why you look in the API and tutorials.

    And remember, you can always use ordinary classes instead of anonymous classes.

    [edit]Oh, I didn't write "save(this);" [/edit]
    [ September 01, 2006: Message edited by: Campbell Ritchie ]
    It is sorta covered in the JavaRanch Style Guide.
    subject: Anynomous