Java weird syntax - (Anonymous subclass)

I came across the strange syntax below, I have never seen such a fragment, this is not a necessity, but it is curious to understand it.

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

Above code is displayed as strange

thanks

+5
source share
3 answers

You created an anonymous subclass of Object , which introduces a method called hi , after which you call this method with the "strange" parameter.

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 exactly in one place, there is no real need to be named, etc. - making it an anonymous class, you will get rid of its name, the class will be defined and instantiated, and the hi method will be called immediately within the same expression.

+9
source

This is completely normal and is called an anonymous class, it is used very often, if you want to pass a reference to a function object, you will do it with anonymous classes or to use callbacks, now .hi at the end is valid because you just used the new operator to create an object of type Object, and you have a link to it to make it work.

0
source

You created an anonymous subclass of the Object class and then call the method. There are four types of anonymous inner class: -

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

In anonymous inner classes, you can define, instantiate and use this inner object, and then

0
source

All Articles