简体   繁体   English

'new' 语句后的花括号有什么作用?

[英]What do curly braces after a 'new' statement do?

I was looking at this example and was wondering what the first line does:我在看这个例子,想知道第一行做了什么:

private SiteStreamsListener listener = new SiteStreamsListener() {

It looks like you can declare additional methods or override methods in this manner.看起来您可以以这种方式声明其他方法或覆盖方法。 Could I, for example, do the following?例如,我可以执行以下操作吗?

ArrayList myList = new ArrayList() {
    @Override String toString()
    {
       <my code here>
    }

    <insert new methods here>
}

These curly braces define an anonymous inner class .这些花括号定义了一个匿名内部类

This allows you to be able to override public and protected methods of the class you are initiating.这使您能够覆盖您正在启动的类的publicprotected方法。 You can do this with any non- final class, but is most useful with abstract classes and interfaces, which can only be initiated this way.您可以对任何非final类执行此操作,但对抽象类和接口最有用,它们只能以这种方式启动。

(To qualify that last sentence, interfaces with only one non- default method can be initiated using lambda statements in Java 8, circumventing this design method.) (为了限定最后一句话,可以使用 Java 8 中的 lambda 语句启动只有一个非default方法的接口,绕过这种设计方法。)

ArrayList myList = new ArrayList() {
  @Override 
  String toString()
  {
    //<my code here>
  }

  //<insert new methods here>
}

Yes you could do that.是的,你可以这样做。 You can defiantly override public,protected methods.您可以大胆地覆盖公共、受保护的方法。 Although you can add new methods but those will not be accessiable through myList instance of ArrayList class.虽然您可以添加新方法,但无法通过 ArrayList 类的 myList 实例访问这些方法。

Please refer to the java documentation for more details.有关更多详细信息,请参阅 java 文档。

https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#declaring-anonymous-classes https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#declaring-anonymous-classes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM