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!
5 Answers 5
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.)
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:
- The syntax is the same for extending classes and implementing interfaces.
- Local variables of the enclosing method are visible, but only those that were declared
final.
Comments
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
Comments
This is the definition of the class. It is called an Anonymous Class.
Comments
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".