47

What do the curly braces do there ?

handler1 = new Handler() {

        public void handleMessage() {

       }
};

object = new Class_Name() {}; ? This syntax exists only on Android or Java also? And what is it called in Java? Thank for your helps.

wanting252
  • 1,139
  • 2
  • 16
  • 22
  • Related / duplicate question : ["Difference between new Test() and new Test() { }"](http://stackoverflow.com/q/22164036/320399) – blong Oct 11 '16 at 16:56

3 Answers3

48

This is the syntax for creating an instance of anonymous class that extends Handler. This is part of Java.

MByD
  • 135,866
  • 28
  • 264
  • 277
3

This is happned when you create the instance reference of the Interface. For example I want to create the instance of the interface Runnable with the class, then I can create it by creating an anonymous class for the same and override the run() method of the interface. You can understand well by looking at the another example other then you stated below.

Runnable runnable = new Runnable() {

    public void run() {
        // TODO Auto-generated method stub

    }
};
Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
0

Instantiates & returns reference of an anonymous subclass of current class.

new Handler() {};
Inside curly braces, definition of anonymous subclass (to be named as Handler$1 by compiler after compilation) can be specified.

It is as equal as extending the Handler class explicitly but it requires name specification obviously of subclass & so it will not remain anonymous any longer.

Following code might help to understand Instantiates & returns reference of an anonymous subclass of current class.
class Main{
    int a = 5;
    void func(){}
    void meth(){
        Main ref2 = new Main() {
            void func(){
                System.out.println(a);
            }           
        };
        ref2.func();
    }    
    public static void main(String[] args) {
        Main mm = new Main();
        mm.meth();
    }
}
//5
YashK
  • 1
  • 2