Anonymous Inner Class in Java
Table of Contents
- Introduction
- What is an Anonymous Inner Class in Java?
- Use Case: Anonymous Inner Classes in Action
- Anonymous Inner Classes vs. Named Inner Classes
- Advantages and Disadvantages of Anonymous Inner Classes
- Conclusion
Introduction
In this chapter, we delve into the concept of anonymous inner classes in Java, a powerful feature that simplifies certain types of coding.
Anonymous inner classes allow developers to make their code more concise when implementing interfaces or abstract classes. This topic is especially useful for those who
seek efficiency and clarity in Java code while minimizing the overhead of defining a full-fledged class. We will explore their usage, benefits, and implementation through detailed code examples and outputs.
What is an Anonymous Inner Class in Java?
An anonymous inner class is a local inner class without a name. It enables you to define and instantiate a class simultaneously. The main use of an
anonymous inner class is to override methods of an abstract class or implement an interface on the fly, especially when you need the class only once.
This approach keeps your code clean and focused.
Key Features
- No Explicit Class Declaration: Unlike regular classes, there is no need to define a new class with a name.
- Immediate Instantiation: The class is both defined and instantiated at the same time.
- Limited Scope: Anonymous inner classes are often used to simplify code when a class is used only once.
- Abstraction: Typically used with abstract classes or interfaces, allowing a quick and concise way to define functionality.
Use Case: Anonymous Inner Classes in Action
Let’s now explore an example to demonstrate how anonymous inner classes can be implemented in Java.
Java Code (Main.java)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Main { public static void main(String[] args) { new Lock() { @Override public void isUnlocked(String key) { if (key.equals("qwerty")){ System.out.println("Shop is open"); } else { System.out.println("Shop is closed"); } } }.isUnlocked("qwerty"); } } |
Supporting Abstract Class (Lock.java)
1 2 3 4 5 6 |
abstract class Lock { public abstract void isUnlocked(String key); public void test() { System.out.println("Test"); } } |
Explanation of the Code:
In the above example:
- Abstract Class (
Lock
):
Lock
is an abstract class that defines an abstract methodisUnlocked(String key)
which takes a string inputkey
and determines if a shop is open or closed.
The class also includes a methodtest()
for demonstration purposes. - Anonymous Inner Class:
In themain()
method of theMain
class, we are creating an anonymous inner class that extends theLock
class and overrides the
isUnlocked
method. We check whether the providedkey
equals"qwerty"
. If the key is correct, it prints"Shop is open"
,
otherwise, it prints"Shop is closed"
. - Execution: The anonymous inner class is created and used immediately to call the
isUnlocked
method with the string"qwerty"
.
Output of the Program
1 |
Shop is open |
Since the key "qwerty"
is passed into the isUnlocked()
method and it matches the expected key, the output will be "Shop is open"
.
If a different key (e.g., "abc123"
) were passed, the output would be "Shop is closed"
because the key would not match the expected value "qwerty"
.
Anonymous Inner Classes vs. Named Inner Classes
Aspect | Anonymous Inner Class | Named Inner Class |
---|---|---|
Class Name | No class name. Defined and instantiated together. | Requires an explicit class name. |
Reusability | Typically used for one-time implementations. | Can be reused in multiple places. |
Instantiation | Instantiated immediately at the point of definition. | Requires separate instantiation after class definition. |
Code Readability | More concise but can be harder to read for complex logic. | Easier to understand for more complex use cases. |
Flexibility | Limited functionality, suited for short, simple use cases. | Full flexibility with access to constructors and methods. |
Advantages and Disadvantages of Anonymous Inner Classes
Advantages
- Conciseness: Eliminates the need to define a separate class.
- Readability: Reduces boilerplate code, especially in short implementations.
- Quick Implementations: Ideal for one-off implementations of interfaces or abstract classes.
Disadvantages
- Limited Scope: Anonymous classes are typically used for simple tasks, not for complex logic.
- Harder Debugging: Since they don’t have a name, it can be difficult to trace errors or understand code flow in large applications.
- Single Use: Cannot be reused, as they are created for one-time use.
Conclusion
Anonymous inner classes are a useful tool in Java for quickly implementing abstract classes or interfaces in a clean and concise way. They are best suited for scenarios where you need to define a class for immediate use and don’t require reusability. By reducing boilerplate code, they allow for a more streamlined coding experience, though their limitations must be taken into account when deciding whether to use them.
For tasks requiring complex logic or reusability, a named class might be a better solution. However, for quick, one-time use cases, anonymous inner classes offer an elegant and efficient solution.