问题
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