java Subclases when i make an object? [duplicate]

血红的双手。 提交于 2019-12-11 04:19:31

问题


Possible Duplicate:
How are Anonymous (inner) classes used in Java?

i have a question about java. i saw this in many sources...

Class object = new Class()
{
    // What is this, a subclass or what ?
    public void someRandomMethod()
    { 
    }
};

umm if is a subclass, when i make the object the class is executed automatically ? I'm confused

and sorry about my english, i try to do my best.

Many thanks !


回答1:


It's called an anonymous class. Yes, the class will automatically be extended. This pattern is most commonly used to create callback interfaces such as Runnable or ActionListener.

Thread foo = new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello World");
    }
});
foo.start(); // Hello World

This creates a new instance of Runnable and passes it to the Thread for execution. This was Java's early substitute for closures.



来源:https://stackoverflow.com/questions/10778578/java-subclases-when-i-make-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!