“object.new”是怎么回事?工作? (Java有.new运算符吗?) [英] How does "object.new" work? (Does Java have a .new operator?)

查看:126
本文介绍了“object.new”是怎么回事?工作? (Java有.new运算符吗?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我在阅读加速GWT(Gupta) - 第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?

有没有人知道在java规范中哪里可以找到这个?

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

推荐答案

他们是内部(嵌套的非静态)类:

They're inner (nested non-static) classes:

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

你可以这样做:

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

或简单地说:

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);
    }
  }
}

并运行:

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

输出:

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();

静态嵌套类通常是 private 因为它们往往是实现细节和封装问题的一部分,而不会污染公共命名空间。

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.

这篇关于“object.new”是怎么回事?工作? (Java有.new运算符吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆