tags:

views:

95

answers:

4

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?

+7  A: 

This construct makes actually two things: 1) It creates an anonymous class which extends the class you use in the constructor and 2) creates an instance of this anonymous class.

Edit: When using such a construct you can observe the anonymous class by looking at the generated .class files. There is the normal MyClass.class file and another one for each anonymous subclass: MyClass$1.class for the first and so on.

ZeissS
So would a good use case be for objects that you're going to use? For example, objects you would immediately put into an array?
andrewheins
My Main use case would be for an implementation of a simple interface (just one method) or to customize an adapter (e.g. java.awt.event. stuff). Another use case is provided by @Nathan-Hughes. Simple Rule: Only do the simplest stuff in an anonymous class and use subclasses / own classes for the rest
ZeissS
That helps, thanks.
andrewheins
Technically speaking, it *declares* a new class rather than creating one. ("Creating" has the implication that something happens at runtime ... which is not the case for the class itself.)
Stephen C
A: 

Second construction creates an instance of anonymous class which is a subclass of Class.

Roman
+3  A: 

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.

Carlos
+3  A: 

You would use the second construct in the case that you want to make an anonymous class. if you have a method that takes a callback as an argument, you might want to specify the implementation of the callback inline as opposed to giving it a name and putting it in a separate file or declaring it elsewhere in the same file.

There's also a trick called double brace initialization where you can get around not having syntax for literal maps and lists by using anonymous classes, like this:

Map map = new HashMap() {{put("foo", 1); put("bar", 2);}};

Here the nested braces create an instance initializer. The object bound to map is not a HashMap, its class is an anonymous class extending HashMap.

Nathan Hughes