nikosdi
nikosdi

Reputation: 2158

java braces usage

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!

Upvotes: 2

Views: 241

Answers (5)

james4563
james4563

Reputation: 169

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

Upvotes: 2

coobird
coobird

Reputation: 161022

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.)

Upvotes: 15

biziclop
biziclop

Reputation: 49804

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.

Upvotes: 4

Konrad Garus
Konrad Garus

Reputation: 54045

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".

Upvotes: 1

Giann
Giann

Reputation: 3192

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

Upvotes: 1

Related Questions