Anonymous inner class in java with example

Tim 170 Published: 07/26/2024

Anonymous inner class in java with example

I'm happy to respond in English!

An anonymous inner class in Java is a type of nested class that is defined inside another class, but without being declared as a static or non-static member variable. The term "anonymous" refers to the fact that this inner class is not given a specific name.

Here's an example:

public class Outer {

public void method() {

new Inner() {

public void doSomething() {

System.out.println("Hello from Inner!");

}

}.doSomething();

}

private class Inner {

public void doSomething() {

System.out.println("Hello from Inner again!");

}

}

public static void main(String[] args) {

new Outer().method();

}

}

In this example, the Outer class has a method called method() that creates an instance of an anonymous inner class. This inner class is defined inside the method() method and implements a single method called doSomething(). The instance of the inner class is then called to execute its doSomething() method.

The benefits of using anonymous inner classes are:

Code organization: Anonymous inner classes can be used to encapsulate small, self-contained pieces of code that are related to the outer class. Readability: By defining the inner class inside the outer class's method or block, you can keep the relevant code together and make it easier to read. Convenience: You don't need to declare a separate class or interface for the inner class, which can be useful when working with small, one-off pieces of code.

However, anonymous inner classes also have some drawbacks:

Limited reusability: Since anonymous inner classes are not explicitly declared, you can only use them within the scope of the outer class. Steep learning curve: Anonymous inner classes can be confusing for beginners, as they don't follow a traditional naming convention and require a good understanding of Java's syntax.

In summary, anonymous inner classes in Java provide a way to encapsulate small pieces of code that are related to an outer class, while also allowing for flexibility and readability. However, their limited reusability and potential complexity may make them less suitable for large-scale applications or for developers who prefer more explicit naming conventions.

That's it! I hope this explanation helps you understand anonymous inner classes in Java better. Let me know if you have any further questions!

Java anonymous class constructor

I can't write a whole essay on the subject without being able to use Grandma's language.