6

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.

Community
  • 1
  • 1
user1070507
  • 123
  • 1
  • 1
  • 3
  • 4
    You can actually try this yourself you know... And also: http://stackoverflow.com/questions/2428186/use-of-class-definitions-inside-a-method-in-java – Tudor Feb 27 '12 at 11:12

4 Answers4

9

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.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
  • There is one good use for local inner classes, namely the case where you need something like an anonymous class but where you need the class to have a constructor. – Mathias Schwarz Feb 27 '12 at 11:17
  • @MathiasSchwarz: You can use initializer blocks for most of those cases - what are you doing in the constructor which requires it to be named? – Jon Skeet Feb 27 '12 at 11:30
  • 1
    Yes that is another way to do it. However, 'parameters' to such initializer blocks would then need to be declared final in the outer scope (the method). – Mathias Schwarz Feb 27 '12 at 13:19
9

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.
        }
      }
    }
  }

}
OldCurmudgeon
  • 62,806
  • 15
  • 115
  • 208
0

Yes, it's called local inner class - you'll find examples by using this term in a web search.

Rostislav Matl
  • 3,988
  • 4
  • 26
  • 52
0

Yes, it is called a local class: Java Language Specification

Franklin Yu
  • 7,543
  • 4
  • 40
  • 50
assylias
  • 310,138
  • 72
  • 642
  • 762