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!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is an anonymous inner class.
Basically, it is a subclass of
AnObjectwithout 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.)javacwill usually name these classes with the containing class with a$and some numeric identifier, such asFoobar$1— you’ll likely find<EnclosingClass>$1.classafter you compile that code.(Where
<EnclosingClass>is the class which contains the anonymous inner class.)