What do curly braces after a 'new' statement do?

前端 未结 2 917
无人共我
无人共我 2021-01-01 07:13

I was looking at this example and was wondering what the first line does:

private SiteStreamsListener listener = new SiteStreamsListener() {
<
相关标签:
2条回答
  • 2021-01-01 07:45
    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.

    Please refer to the java documentation for more details.

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

    0 讨论(0)
  • 2021-01-01 07:48

    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. 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.

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

    0 讨论(0)
提交回复
热议问题