Question

How is it helpful to use anonymous class if every time we have to define a class while invoking a constructor of an interface.Wouldn't it be more better to simple use a generic type instead?

Was it helpful?

Solution

Anonymous classes is frequently used in GUI applications. When you only need to declare and create object of a class at the same time, it can make the code more precise.

Here is an example:

        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });

OTHER TIPS

Anonymous classes are not defined every time they are instantiated. They get compiled into bytecode just like other classes, with a name e.g. MyEnclosingClass$1. See this post for more information: How are anonymous classes compiled in Java?

Tangentially, reflection can be used to identify them at runtime using Class.isAnonymousClass().

It depends on the situation; in some cases it will be better to use an anonymous class, and in others, it will be better to use a concrete class that implements the required interface.

If you believe that you'll need to provide the same anonymous class definition repeatedly, it will likely save you time to pass an instance of a concrete class that implements the required interface.

The Java language provides anonymous class syntax as a convenience.

To give you just a taste, here's a quick example from my own experience: Having lists backed by functions.

In general, anonymous classes have (among others) the following uses:

  • Suppose you want to have an object (an instance, not a class) whose behavior depends on some value available at runtime. Without anonymous classes, you can do this by setting fields (or calling state-changing methods) - but you can't have different code executing. Now, true, you could have bunch of switch() statements in your class' method code - but that completely decouples the definition of the behavior from its context. Another way you could go is to use a named subclass, but that's a lot of code, and it creates a noun you don't really want to exist.
  • Functional Programming! Until Java 8 comes along, anonymous functions are just about the only way you can pass around functions, which are not first-class citizens in Java. With those, you can perform many neat and elegant tricks like my example above.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top