2015-04-03 42 views
0

我看着this example和不知道第一线的作用:“新”陈述后的大括号是什么?

private SiteStreamsListener listener = new SiteStreamsListener() { 

看起来你可以声明额外的方法或覆盖以这种方式方法。例如,我可以做以下事情吗?

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

    <insert new methods here> 
} 
+0

请避免提问只能由编译器回答的问题。你为什么不编译该代码,看看是否有可能? – 2015-04-03 19:58:00

+1

即使你可以插入新的方法,只有'ArrayList'中的方法才会可见,因为这就是对象声明为 – chancea 2015-04-03 19:58:11

+0

至于那些大括号的用途,请看[这篇文章](http://stackoverflow.com/ q/22164036/1679863) – 2015-04-03 19:58:17

回答

3

这些大括号定义了一个anonymous inner class

这使您可以覆盖您正在启动的类的publicprotected方法。您可以使用任何非final类来完成此操作,但对抽象类和接口最为有用,只能以此方式启动。

(要获得最后那句话,只有一个非default方法接口可以在Java中使用8拉姆达声明,规避这种设计方法来启动。)