How does "object.new" work? (Is there a .new operator in Java?)

I came across this code today while reading the 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 the new operators doing there? I have never seen such a syntax, can anyone explain?

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

+59
java syntax inner-classes
May 19 '10 at 5:47 a.m.
source share
3 answers

They are internal (nested non-static) 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. nested classes can be static too. If so, they do not have an implicit this reference for the outer class:

 public class Outer { public static class Nested { public void foo() { System.out.println("Foo"); } } } new Outer.Nested.foo(); 

Most often, static nested classes are private , since they are usually implementation details and a neat way to encapsulate part of the problem without polluting the public namespace.

+58
May 19 '10 at 5:50
source share

BookListUpdaterCallback and StoreOrderCallback are inner classes of BookStore.

See the Java Tutorial - http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html and http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

+3
May 19 '10 at 5:51 a.m.
source share

I haven't seen this syntax yet, but I think it will create an internal BookStore class.

+2
May 19 '10 at 5:49 a.m.
source share



All Articles