2

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!

mikej
66.6k18 gold badges156 silver badges131 bronze badges
asked Jun 28, 2011 at 14:30

5 Answers 5

15

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 Foobar1ドル -- you'll likely find <EnclosingClass>1ドル.class after you compile that code.

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

answered Jun 28, 2011 at 14:32
Sign up to request clarification or add additional context in comments.

2 Comments

Without checking, I think you'll find a <enclosingClass>1ドル.class after you compile that code.
@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! :)
4

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.
answered Jun 28, 2011 at 14:35

Comments

2

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

answered Jun 28, 2011 at 14:35

Comments

1

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

answered Jun 28, 2011 at 14:32

Comments

1

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

answered Jun 28, 2011 at 14:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.