4

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 ?

4

1 に答える 1

2

唯一の違いは、例 1 のクラスは名前付きで、例 2 のクラスは無名であることです。機能的には、それ以外は同じです。

代わりにクラスを次のように宣言した場合

static class MyHandler implements ClickHandler ...

次に、内部クラスとは異なる静的なネストされたクラスになります。前者には、囲んでいるクラスのメソッドへの参照または直接アクセスがありません。

于 2012-10-11T15:33:11.833 に答える