Home » Android » java – Curly braces in "new" expression? (e.g. "new MyClass() { … }")

java – Curly braces in "new" expression? (e.g. "new MyClass() { … }")

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

How to&Answers:

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

Answer:

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

    }
};