Curly braces in “new” expression? (e.g. “new MyClass() { … }”)

前端 未结 3 697
鱼传尺愫
鱼传尺愫 2020-11-28 13:37

What do the curly braces do there ?

handler1 = new Handler() {

        public void handleMessage() {

       }
};

object = new Class

3条回答
  •  攒了一身酷
    2020-11-28 14:03

    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
    

提交回复
热议问题