Nitesh Virani
Nitesh Virani

Reputation: 1712

Java strange syntax - (Anonymous sub-class)

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

Upvotes: 5

Views: 171

Answers (3)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

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.

Upvotes: 9

abc
abc

Reputation: 2027

This is perfectly normal and is Called an anonymous class it is used very often where if u want to pass an object reference to a function you will do it with anonymous classes or for the use of callbacks, now .hi at the end is valid because you just used the new operator to instantiate an object of type Object and you have a reference to it so that's why it works.

Upvotes: 0

Kumar Abhinav
Kumar Abhinav

Reputation: 6675

You've created an annonymous sub-class of Object and then invoke the method. Four types of anonymous inner class exists :-

1)Inner class,
2)Static nested classes
3)Method local inner classes
4)Anonymous inner classes

In Annonymous inner classes,you can define,instantiate and use that inner object then and there

Upvotes: 0

Related Questions