简体   繁体   中英

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

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.

这是完全正常的,被称为匿名类,它经常使用,如果您想将对象引用传递给函数,则可以使用匿名类或使用回调来实现,现在.hi结尾是有效的,因为您只是使用new运算符实例化了Object类型的对象,并且对其具有引用,因此这才起作用。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM