1

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?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
masterofdisaster
  • 1,079
  • 1
  • 12
  • 27
  • 3
    What "name that we provide"? The whole point of an anonymous class is that you didn't explicitly define it with a name. – azurefrog Feb 26 '18 at 18:02
  • 2
    No, it's not because the compiler does not include the name, it's because we literally do not provide a name for these classes. – Sergey Kalinichenko Feb 26 '18 at 18:03
  • You should read this: https://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java – azurefrog Feb 26 '18 at 18:03
  • 2
    *why they are also called classes without a name?* Because they have no name. Don't confuse interface name and class name: `new ActionListener() {/* anonymous class implementation */}` -> here `ActionListener` is **not** the anonymous class name, it's just the interface name. The anonymous class is the implementation (code between curly braces) and as you can see it has no name. – BackSlash Feb 26 '18 at 18:03
  • Ok now i get it, thank you :) – masterofdisaster Feb 26 '18 at 18:12
  • Anonymous classes just like any class have names. The only difference is that the name is auto generated. – tsolakp Feb 26 '18 at 18:15

1 Answers1

2

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.

Community
  • 1
  • 1
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138