Possible Duplicate:
Use of class definitions inside a method in Java
Can we have inner class inside a method ?
Any code sample will be helpful.
Possible Duplicate:
Use of class definitions inside a method in Java
Can we have inner class inside a method ?
Any code sample will be helpful.
Yes you can.
public final class Test {
// In this method.
private void test() {
// With this local variable.
final List<String> localList = new LinkedList<String>();
// We can define a class
class InnerTest {
// Yes you can!!
void method () {
// You can even access local variables but only if they are final.
for ( String s : localList ) {
// Like this.
}
}
}
}
}
Yes, you can:
public static void main(String[] args) {
class Foo implements Runnable {
@Override public void run() {
System.out.println("Hello");
}
}
Foo foo = new Foo();
}
I would recommend against it though, preferring anonymous inner classes where they're good enough, or nested classes not inside the method in other cases. If you need a named class within a method, that suggests you need to get at extra members it declares, which is going to get messy. Separating it into its own nested class (ideally making it static, to remove a bunch of corner cases) usually makes the code clearer.
Yes, it's called local inner class - you'll find examples by using this term in a web search.
Yes, it is called a local class: Java Language Specification