Reputation: 2158
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
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
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
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:
final
.Upvotes: 4
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
Reputation: 3192
This is the definition of the class. It is called an Anonymous Class.
Upvotes: 1