Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java strange syntax - (Anonymous sub-class)

Tags:

java

I have come across below strange syntax, I have never seen such snippet, it is not necessity but curious to understand it

new Object() {
    void hi(String in) {
        System.out.println(in);
    }
}.hi("strange");

Above code gives output as strange

thanks

like image 942
Nitesh Virani Avatar asked Aug 07 '15 06:08

Nitesh Virani


1 Answers

You've created an anonymous sub-class of Object, which introduces a method, called hi, after which you invoke this method with parameter "strange".

Let's suppose you had:

class NamedClass extends Object {
    void hi(String in) { System.out.println(in); }
}

NamedClass instance = new NamedClass();
instance.hi("strange");

If this class was needed at exactly one place, there's no real need of being named and so on - by making it an anonymous class, you get rid of its name, the class gets defined and instantiated and the hi method invoked immediately within a single expression.

like image 193
Konstantin Yovkov Avatar answered Nov 10 '22 01:11

Konstantin Yovkov