I\'ve been examining the Java Language Specification here (instead I should be out having a beer) and I am curious about what a method can contain. The specification states a me
As others have said, you can declare a class inside a method. One use case of this is to use this as an alternative for an anonymous inner class. Anonymous inner classes have some disadvantages; for example, you can't declare a constructor in an anonymous inner class. With a class declared locally in a method, you can.
Here's a silly example that doesn't really show why you'd want to do this, but at least how you could do it.
public Runnable createTask(int a, int b) {
// Method-local class with a constructor
class Task implements Runnable {
private int x, y;
Task(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void run() {
System.out.println(x + y);
}
}
return new Task(a, b);
}