views:

282

answers:

3

I came across this code today whilst reading Accelerated GWT (Gupta) - page 151.

public static void getListOfBooks(String category, BookStore bookStore) {
    serviceInstance.getBooks(category, bookStore.new BookListUpdaterCallback());
}
public static void storeOrder(List books, String userName, BookStore bookStore) {
    serviceInstance.storeOrder(books, userName,    bookStore.new StoreOrderCallback());
}

What are those new operators doing there? I've never seen such syntax, can anyone explain?

Does anyone know where to find this in the java spec?

+1  A: 

I haven't seen this syntax before either, but I think it will create an inner class of BookStore.

tangens
+22  A: 

They're nested inner classes:

public class Outer {
  public class Inner { public void foo() { ... } }
}

You can do:

Outer outer = new Outer();
outer.new Inner().foo();

or simply:

new Outer().new Inner().foo();

The reason for this is that Inner has a reference to a specific instance of the outer class. Let me give you a more detailed example of this:

public class Outer {
  private final String message;

  Outer(String message) {
    this.message = message;
  }

  public class Inner {
    private final String message;

    public Inner(String message) {
       this.message = message;
    }

    public void foo() {
      System.out.printf("%s %s%n", Outer.this.message, message);
    }
  }
}

and run:

new Outer("Hello").new Inner("World").foo();

Outputs:

Hello World

Note: inner classes can be static too. If so, they have no implicit this reference to the outer class:

public class outer {
  public static class Inner {
    public void foo() { System.out.println("Foo"); }
  }
}

new Outer.Inner().foo();

More often than not, static inner classes are private as they tend to be implementation details and a neat way of encapsulating part of a problem without polluting the public namespace.

cletus
Ah I see - thanks!
Ash Kim
It's all spelled out here if anyone's hazy on this: http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
Ash Kim
and also a good discussion here: http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class
Ash Kim
+1  A: 

BookListUpdaterCallback and StoreOrderCallback are inner classes of BookStore.

See The Java Tutorial - http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html and http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

Greg Case