3

Is there any benefit to define a class inside a method. I saw someone prefer to define some listener class inside a method, any real benefit to do this?

Adam Lee
  • 24,710
  • 51
  • 156
  • 236
  • possible duplicate of [Use of class definitions inside a method in Java](http://stackoverflow.com/questions/2428186/use-of-class-definitions-inside-a-method-in-java) – Luke Girvin Jun 09 '12 at 10:17

3 Answers3

5

I think you mean anonymous inner classes or local inner classes. See this article for the differences and the advantages In my opinion, the biggest advantage is that the code is at the place where it is used and not in another file.

theomega
  • 31,591
  • 21
  • 89
  • 127
3

It's done for two reasons:

  • Locality of logic. Scatterring logically and tightly related parts of code makes it harder to follow.
  • When you define a class inside a method, it closes in over the local variables available in scope. This way unnecessary argumet passing is avoided.
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
1

It is named InnerClass, and this allows you to instantiate an object that implements an interface or abstract class without the need to define it formally as a separated class. Listeners are good examples since it would be too costly to support a system that has every single listener implemented as a separated class.

A good reference: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html (Inner Classes topic)

Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
  • I think he is not talking about nested Classes but inner classes. The doc you pointed to is talking aboiut nested Classes. – theomega Jun 09 '12 at 10:20
  • Additional link (specific for inner-class): http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html. – Francisco Spaeth Jun 09 '12 at 10:21