Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

syntax - How does "object.new" work? (Does Java have a .new operator?)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They're inner (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 have no implicit this reference to the outer class:

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

new Outer.Nested.foo();

More often than not, static nested 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...