Take the 2-minute tour ×

I have a java code similar to this:

AnObject anObject = new AnObject() {
    int count;
    public int creation() {
        return count;

I can't understand the meaning of the braces. A class following the constructor? Thank you!

share|improve this question
add comment

5 Answers

up vote 15 down vote accepted

It is an anonymous inner class.

Basically, it is a subclass of AnObject without a name.

It's anonymous because it does not have a class name declaration (e.g. class Foo), and it is an inner class because it is defined within another class (which does not seem to be shown in the code provided.)

javac will usually name these classes with the containing class with a $ and some numeric identifier, such as Foobar$1 -- you'll likely find <EnclosingClass>$1.class after you compile that code.

(Where <EnclosingClass> is the class which contains the anonymous inner class.)

share|improve this answer
Without checking, I think you'll find a <enclosingClass>$1.class after you compile that code. –  Puce Jun 28 '11 at 15:05
@Puce I checked and you're correct -- it is the name of the enclosing class that is used in the class file's name. Editing the answer. Thanks! :) –  coobird Jun 28 '11 at 15:15
add comment

It's an anonymous inner class.

The code is almost the same as:

private class Foo extends AnObject {
   int count;
   public int creation() { return count; }
AnObject anObject = new Foo();

There are some subtle differences though:

  1. The syntax is the same for extending classes and implementing interfaces.
  2. Local variables of the enclosing method are visible, but only those that were declared final.
share|improve this answer
add comment

It is creating an anonymous inner class.

There is some very useful tutorials on the following site about anonoymous inner classes. Anonymous Inner class tutorials

share|improve this answer
add comment

This is the definition of the class. It is called an Anonymous Class.

share|improve this answer
add comment

In this case the curly braces are used for creating an anonymous subclass of AnObject. Inside the braces are new fields and methods as methods overriding the superclass. This pattern is very common for simpler abstract classes or interfaces, such as creating a listener "in place".

share|improve this answer
add comment

Your Answer


