09.08. Anonymous Inner Class

Anonymous Inner Class

  • Eclipse: Oxygen
  • Java: 1.8

In Java, an anonymous inner class is a class that is defined and instantiated simultaneously without explicitly providing a name for the class. It is a convenient way to implement interfaces or extend classes on-the-fly, right at the point of use. This powerful feature allows for concise and localized implementations, enhancing code readability and maintainability.

It is useful when you need to implement a class or interface for a specific instance or scenario, but you don’t need to reuse it elsewhere in your code.

An anonymous inner class is created by specifying the interface to be implemented or the superclass to be extended, followed by an opening and closing brace that encloses the implementation code.

Project Folder Structure

Door.java

Explanation:

The Door class represents a door with a lock. It has a private instance variable called lock, which is an instance of the Lock interface. In this code, an anonymous inner class is used to implement the Lock interface directly within the Door class. The Lock interface has one abstract method called isUnlocked, which is implemented in the anonymous inner class. The isUnlocked method takes a keyCode as a parameter and returns true if the keyCode is equal to “qwerty”, indicating that the door is unlocked.
The Door class also has a getLock method that returns the instance of the Lock interface.

Lock.java

In the following program, we create an abstract class lock.

Explanation:

The Lock class is an abstract class that defines a single abstract method isUnlocked(String keyCode). It has one abstract method called isUnlocked, which takes a keyCode as a parameter and returns a boolean indicating whether the lock is unlocked or not. The Lock class serves as a blueprint for implementing different types of locks.

Shop.java

Explanation:

The Shop class contains the main method and acts as the entry point of the program. In the main method, a new instance of the Door class is created. The isUnlocked method of the Lock interface is invoked on the lock object obtained from the Door instance, passing the first command-line argument (args[0]) as the keyCode. If the isUnlocked method returns true, it means the door is unlocked, and the message “Welcome, we are open” is printed. Otherwise, if the isUnlocked method returns false, the message “We are closed now, please visit later” is printed.

This code demonstrates the concept of encapsulation, where the Door class encapsulates the Lock functionality, and the Lock class defines the contract for implementing locks. The Shop class then uses the Door and Lock classes to check whether the shop is open or closed based on the provided keyCode.

Output

The output of the program will depend on the command-line argument(args[0]) passed when running the program. Let’s analyze the possible scenarios and their corresponding outputs:

  1. If the command-line argument is “qwerty”:
    • The isUnlocked method of the Lock interface is called with “qwerty” as the keyCode.
    • Since the implementation in the anonymous inner class of the Door class checks if the keyCode is equal to “qwerty”, it will return true.
    • The condition if(door.getLock().isUnlocked(args[0])) in the Shop class will evaluate to true.
    • Therefore, the output will be “Welcome, we are open”.
  2. If the command-line argument is any other value than “qwerty”:
    • The isUnlocked method of the Lock interface is called with the provided keyCode.
    • Since the implementation in the anonymous inner class of the Door class checks if the keyCode is equal to “qwerty”, it will return false.
    • The condition if(door.getLock().isUnlocked(args[0])) in the Shop class will evaluate to false.
    • Therefore, the output will be “We are closed now, please visit later”.

If the keyCode passed as a command-line argument is “qwerty”, the program will output “Welcome, we are open”. Otherwise, if any other keyCode is provided, the program will output “We are closed now, please visit later”.

Usage


  1. Implementing Interfaces: Anonymous inner classes are commonly used to implement interfaces with a single abstract method (functional interfaces) such as event listeners or callback interfaces. Instead of creating a separate class that implements the interface, an anonymous inner class can be used to define the implementation inline. This simplifies the code by keeping the implementation localized and focused.
  2. Extending Classes: Anonymous inner classes can also be used to extend concrete or abstract classes. By providing the necessary implementation within the anonymous inner class, you can override methods or add new functionality to the superclass without explicitly creating a separate class.

Benefits


  1. Concise and Readable Code: Anonymous inner classes allow you to define and implement functionality right where it is needed, avoiding the need for separate classes. This leads to more compact and readable code by keeping related code closer together.
  2. Enhanced Encapsulation: Since anonymous inner classes are defined within a specific scope, they have access to the variables and methods of the enclosing class. This encapsulation ensures that the implementation code is localized and can easily interact with the surrounding context.
  3. On-the-Fly Customization: Anonymous inner classes provide a convenient way to customize the behavior of interfaces or classes without the overhead of defining separate classes. This flexibility is particularly useful when the customization is specific to a particular use case and not needed elsewhere.

Considerations:

  1. Limited Reusability: Anonymous inner classes are primarily useful for one-time or localized implementations. If the same implementation needs to be reused in multiple places, it is better to define a separate named class or consider using lambda expressions in Java 8+.
  2. Class Size and Complexity: While anonymous inner classes provide a concise implementation approach, they can sometimes result in larger and more complex code blocks. It is essential to strike a balance between brevity and readability to ensure maintainability.

Conclusion

Java anonymous inner classes offer a powerful mechanism for implementing interfaces and extending classes with minimal ceremony. By combining the definition and instantiation in one step, they promote code locality and enhance code readability. However, it is important to use them judiciously, considering reusability and code complexity. With their flexibility and convenience, anonymous inner classes are a valuable tool in the Java developer’s arsenal, enabling elegant and focused implementations.

Remember to leverage the power of anonymous inner classes when you need concise, localized implementations of interfaces or customized extensions of classes. By mastering this feature, you can write more expressive and maintainable Java code.

Reference: https://wiki.c2.com/?AnonymousInnerClass

Contributed by: Salim Sheikh

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments