5

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>
}
Teofrostus
  • 1,506
  • 4
  • 18
  • 29
  • 2
    Even if you could insert new methods only the methods from `ArrayList` would be visible because that's what the object is declared as – chancea Apr 03 '15 at 19:58
  • As for what those braces are for, look into [this post](http://stackoverflow.com/q/22164036/1679863) – Rohit Jain Apr 03 '15 at 19:58
  • It's an anonymous inner class definition of an interface or abstract class. – Ryan J Apr 03 '15 at 19:58
  • 3
    @RohitJain My question cannot be simply answered by a compiler, because a compiler will not tell me the actual function of the braces, only whether or not the code can compile. I was looking for an answer such as the one I accepted, which gives the terminology for this instance so that I could gain an understanding of what is actually happening. In general, I feel that bouncing questions off of a compiler typically causes problems due to the lack of understanding and actual learning taking place: a problem which many students fall prey to. – Teofrostus Apr 04 '15 at 01:03
  • 2
    @Teofrostus I was talking about 2nd part of your question (*whether this will work or not*), not the 1st part (*for which I linked a duplicate in my 2nd comment, if only you looked clearly*). – Rohit Jain Apr 04 '15 at 04:55

2 Answers2

12

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

k_g
  • 4,333
  • 2
  • 25
  • 40
2
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

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Himanshu Ahire
  • 677
  • 5
  • 18