Search code examples
javaclass

Differences between anonymous inner classes and local classes


Possible Duplicate:
Anonymous vs named inner classes? - best practices?

When working with Java Handlers in general, people often use three approaches :

  1. Create a class that will implements all needed interfaces
  2. Create a anonymous inner class
  3. Create a local class

I'm interested only about the differences between 2) and 3)

Comparing 2) to 3) we can consider the following code. In this example, only one class will be generated by the Compiler.

class MyHandler implements ClickHandler, DragHandler, MovedHandler
    {
        public void onClick(ClickEvent clickEvent)
        {
            // Do stuff
        }

        public void onMoved(MovedEvent movedEvent) {
            // Do stuff
        }

        public void onDrag(DragEvent event) {
            // Do stuff
        }
    }

    MyHandler localHandler = new MyHandler();
    button.addClickHandler(localHandler);
    something.addDragHandler(localHandler);
    that.addMovedHandler(localHandler);

In the following example, three inner classes will be generated by the Compiler (correct me if I'm wrong).

button.addClickHandler(new ClickHandler()
    {
        public void onClick(ClickEvent clickEvent)
        {
            // Do stuff
        }
    });
something.addDragHandler(new DragHandler()
    {
        public void onDrag(DragEvent event)
        {
            // Do stuff
        }
    });
that.addMovedHandler(new MovedHandler()
    {
        public void onMoved(MovedEvent movedEvent)
        {
            // Do stuff
        }
    });

My question is : Is there any other difference between these two approaches ? Is there any caveats of using one despite the other ?


Solution

  • The only difference is that the classes in example 1 are named and the classes in example 2 are anonymous. Functionally they are the same otherwise.

    If you instead declared the class like

    static class MyHandler implements ClickHandler ...
    

    Then what you would have would be a static nested class which differs from the inner class in that the former does not have a reference or direct access to the methods of the enclosing class.