Teofrostus
Teofrostus

Reputation: 1636

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

Upvotes: 6

Views: 5279

Answers (2)

Himanshu Ahire
Himanshu Ahire

Reputation: 717

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

  //<insert new methods here>
}

Yes you could do that. You can definitely override public,protected methods. Although you can add new methods but those will not be accessable through myList instance of ArrayList class.

Please refer to the java documentation for more details.

Upvotes: 4

k_g
k_g

Reputation: 4483

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

Upvotes: 15

Related Questions