7

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
  • 133
  • 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

11

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
  • 64,482
  • 16
  • 119
  • 213
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,421,763
  • 867
  • 9,128
  • 9,194
  • 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
0

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

Rostislav Matl
  • 4,294
  • 4
  • 29
  • 53
0

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

Franklin Yu
  • 8,920
  • 6
  • 43
  • 57
assylias
  • 321,522
  • 82
  • 660
  • 783