Differences between anonymous inner classes and local classes

Possible duplicate:
Anonymous vs called inner classes? - best practics?

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

  • Create a class that will implement all the necessary interfaces.
  • Create anonymous inner class
  • Create a local class

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

Comparing 2) with 3), we can consider the following code. In this example, the compiler will generate only one class .

 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 am 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 the two approaches? Are there any reservations about using one, despite the other?

+4
source share
1 answer

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 a 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 reference or direct access to the methods of the enclosing class.

+2
source

Source: https://habr.com/ru/post/1439200/


All Articles