Just out of curiosity, anyone knows what make people think it would be helpful to allow class definition within a method in Java?
For example, I can do this:
public void foo()
{
class Bar
{
}
}
Just out of curiosity, anyone knows what make people think it would be helpful to allow class definition within a method in Java?
For example, I can do this:
public void foo()
{
class Bar
{
}
}
Slightly modified from http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Why Use Local Classes?
Compelling reasons for using local classes include the following:
It is a way of logically grouping classes that are only used in one method: If a class is useful to only one method, then it is logical to embed it in that method and keep the two together. Nesting such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider a private helper method foo() and a class B, where B needs access to arguments of foo(). By hiding class B within foo(), foo() can be kept private and B can access foo()'s arguments. In addition, B itself can be hidden from the outside world.
It can lead to more readable and maintainable code: Nesting small classes within methods places the code closer to where it is used.
This sort of thing is usually used to create anonymous inner classes, although they will mostly be replaced by closures in Java 8.
They are mostly useful for listeners, where the code to process the result of a method can now be written in the same place as the code to call the method.
Basically encapsulation says that you should keep as much as you can within your program as restricted as you can. The more encapsulated you make everything the easier to maintain your program becomes as there are less unexpected inter-dependencies.