`someObject.new`在Java中做什么? [英] What does `someObject.new` do in Java?

查看:108
本文介绍了`someObject.new`在Java中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我刚刚发现以下代码是合法的:

In Java, I have just found out that the following code is legal:

KnockKnockServer newServer = new KnockKnockServer();                    
KnockKnockServer.receiver receive = newServer.new receiver(clientSocket);

仅供参考,接收方只是一个带有以下签名的帮助类:

FYI, receiver is just a helper class with the following signature:

public class receiver extends Thread {  /* code_inside */  }

之前我从未见过 XYZ.new 表示法。这是如何运作的?是否有任何方法可以更传统地编码?

I've never seen the XYZ.new notation before. How does that work? Is there any way to code that more conventionally?

推荐答案

这是从包含外部实例化非静态内部类的方法类主体,如 Oracle文档中所述。

It's the way to instantiate a non-static inner class from outside the containing class body, as described in the Oracle docs.

每个内部类实例都与其包含类的实例相关联。当 new 中包含类的内部类时,它使用实例默认情况下容器:

Every inner class instance is associated with an instance of its containing class. When you new an inner class from within its containing class it uses the this instance of the container by default:

public class Foo {
  int val;
  public Foo(int v) { val = v; }

  class Bar {
    public void printVal() {
      // this is the val belonging to our containing instance
      System.out.println(val);
    }
  }

  public Bar createBar() {
    return new Bar(); // equivalent of this.new Bar()
  }
}

但是如果你想在Foo之外创建一个Bar实例,或者将一个新实例与 this 以外的包含实例相关联,那么你必须使用前缀表示法。

But if you want to create an instance of Bar outside Foo, or associate a new instance with a containing instance other than this then you have to use the prefix notation.

Foo f = new Foo(5);
Foo.Bar b = f.new Bar();
b.printVal(); // prints 5

这篇关于`someObject.new`在Java中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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