1

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 !

Community
  • 1
  • 1
Kai
  • 281
  • 1
  • 5
  • 11

1 Answers1

3

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.

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
  • but i can't use that way for simple object-classes ? like the example, or it's only valid for runnable - actionlistener objects ? – Kai May 28 '12 at 02:11
  • @Kai You can use it for any class you can extend. It wouldn't make sense to create any non-overridden methods in an anonymous class, you wouldn't be able to call them. – Jeffrey May 28 '12 at 02:22