Java - Anonymous Classes

Hello there, future Java wizards! Today, we're going to embark on an exciting journey into the world of Anonymous Classes in Java. Don't worry if you're new to programming; I'll guide you through this concept step by step, with plenty of examples and explanations. So, let's dive in!

Java - Anonymous Class

What are Anonymous Classes?

Imagine you're at a masquerade ball. Everyone's wearing masks, and you can't tell who's who. That's kind of like anonymous classes in Java - they're classes without names, hidden behind a mask of code!

An anonymous class is a special type of inner class that doesn't have a name. It's declared and instantiated in a single expression using the new keyword.

Why Use Anonymous Classes?

  1. They're great for one-time use.
  2. They help keep your code concise.
  3. They're perfect for implementing simple interfaces or extending classes on the fly.

How to Define an Anonymous Class

Let's start with a simple example:

interface Greeting {
    void greet();
}

public class AnonymousClassDemo {
    public static void main(String[] args) {
        Greeting englishGreeting = new Greeting() {
            @Override
            public void greet() {
                System.out.println("Hello, World!");
            }
        };

        englishGreeting.greet();
    }
}

In this example, we've created an anonymous class that implements the Greeting interface. Let's break it down:

  1. We define a simple Greeting interface with one method, greet().
  2. In the main method, we create an instance of Greeting using an anonymous class.
  3. The anonymous class provides an implementation for the greet() method.
  4. We call the greet() method on our englishGreeting object.

When you run this code, it will print "Hello, World!" to the console.

Types of Anonymous Inner Classes in Java

There are three main types of anonymous inner classes in Java:

  1. Anonymous class that extends a class
  2. Anonymous class that implements an interface
  3. Anonymous class that defines inside method/constructor argument

Let's look at examples of each:

1. Anonymous Class that Extends a Class

abstract class Animal {
    abstract void makeSound();
}

public class AnonymousClassExtend {
    public static void main(String[] args) {
        Animal dog = new Animal() {
            @Override
            void makeSound() {
                System.out.println("Woof! Woof!");
            }
        };

        dog.makeSound();
    }
}

In this example, we're creating an anonymous class that extends the abstract Animal class and provides an implementation for the makeSound() method.

2. Anonymous Class that Implements an Interface

We've already seen this in our first example, but here's another one:

interface Calculatable {
    int calculate(int a, int b);
}

public class AnonymousClassImplement {
    public static void main(String[] args) {
        Calculatable adder = new Calculatable() {
            @Override
            public int calculate(int a, int b) {
                return a + b;
            }
        };

        System.out.println("5 + 3 = " + adder.calculate(5, 3));
    }
}

This anonymous class implements the Calculatable interface and provides an implementation for the calculate() method that adds two numbers.

3. Anonymous Class Inside Method/Constructor Argument

public class AnonymousClassArgument {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Anonymous thread is running!");
            }
        });

        t.start();
    }
}

Here, we're creating an anonymous class that implements the Runnable interface directly as an argument to the Thread constructor.

When to Use Anonymous Classes

Anonymous classes are particularly useful when:

  1. You need to implement an interface or extend a class for a one-time use.
  2. The implementation is very short and simple.
  3. You want to avoid creating a separate named class for a simple operation.

However, if you find yourself reusing the same anonymous class multiple times, it might be better to create a named class instead.

Limitations of Anonymous Classes

While anonymous classes are powerful, they do have some limitations:

  1. They can only implement one interface or extend one class at a time.
  2. They cannot have static initializers or member interfaces.
  3. They cannot have constructors (since they don't have a name).

Conclusion

Anonymous classes in Java are like secret agents in your code - they come in, do their job, and disappear without leaving a trace (or a name). They're a powerful tool for creating quick, one-time-use classes that can make your code more concise and readable.

Remember, like with any programming concept, practice makes perfect. Try creating your own anonymous classes and experiment with different use cases. Before you know it, you'll be wielding anonymous classes like a true Java ninja!

Happy coding, and may your anonymous classes always greet you with a cheerful "Hello, World!"

Credits: Image by storyset