1

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
  {
  }
}
3

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Which syntax? The Bar class is not anonymous.
@SotiriosDelimanolis Yeah, good point - reworded slightly.
0

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.

7 Comments

nested class != local class. Nested classes are defined within another class, but local classes are defined within a method.
@eis From JLS, A local class is a nested class (§8).
@eis A local class IS A nested class that is nested inside of a method.
Well, ok. Local class is a certain kind of nested class, but still, nested class is a different concept from local class. OP was asking for local classes in particular.
@eis No, your use might be different. The Java Language Specification is the only valid resource to validate terminology and it clearly says that a local class is a nested class.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.