I am a little bit confused about the explanation of the anonymous classes in Java.
I understand the purpose of such classes, but why are they called classes without a name? Is it because the compiler do not include the name that we provide?
I am a little bit confused about the explanation of the anonymous classes in Java.
I understand the purpose of such classes, but why are they called classes without a name? Is it because the compiler do not include the name that we provide?
The name we provide is not the name of the anonymous class, it's the name of the interface we're implementing or the class we're extending.
Consider the example from the Anonymous Classes tutorial:
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
/* ... */
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
}
Clearly we already have something named HelloWorld
, so the class is not that, it's a new class which implements HelloWorld
.
Also from the above tutorial:
The anonymous class expression consists of the following:
The new operator
The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.