Alex Rivera | Logout

new Object { } Construct

Asked 2010-09-10T21:33:07.217
30

In Java, the standard way to create an object is using

MyClass name = new MyClass();

I also often see the construct

new MyClass() { /*stuff goes in here*/ };

I've been looking online for a while and can't find a good explanation of what the second construct style does or how it does it.

Can someone please explain how and why you would use the second construct?

Edit
Report

1 Answer

8

As others have already said, it creates an instance of an anonymous class, subclassing Class. Here's an example how it is commonly used:

panel.addMouseListener(
  new MouseAdapter () {
    @Override
    public void mouseEntered(MouseEvent e) {
      System.out.println(e.toString());
    }
  }
);

The above code creates an instance of an anonymous class which extends MouseAdapter. In the anonymous class the method mouseEntered has been overridden to demonstrate that the anonymous class works basically as any other class. This is very convenient and common way to create (usually simple) listeners.

answered 2010-09-10T21:44:42.737

Your Answer