Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement an interface using an anonymous inner class in Java?
What is an Anonymous Inner Class
In Java, an anonymous inner class is a class that doesn't have a name, we will directly define it at the time of instantiation. You can use it in cases where you need to override methods of a class (or interface) only once, without creating a separate named class.
Syntax of Anonymous Inner Class
When you are using a class to create an anonymous inner class in Java, use the following syntax:
Class objectName = new Class() {
// Override necessary methods
};
When you are implementing an interface using an anonymous inner class in Java, use the syntax given below:
Interface objectName = new Interface() {
// Override necessary methods
};
Implementing Interface using Anonymous Inner Class
An Interface is a type of class that is defined using the keyword interface. To access its members within a class, we need to use the implements keyword while defining that class. However, you can implement it using an anonymous inner class just by overriding the interface's methods without creating a separate named class.
Example
In the following Java program, we implement the combustion() method of the Oxygen interface using an anonymous inner class and print its output statement.
// interface Oxygen
interface Oxygen {
void combustion();
}
public class CO2 {
public static void main(String[] args) {
// implementing Oxygen using anonymous inner class
Oxygen fire = new Oxygen() {
@Override
public void combustion() {
System.out.println("Fire needs Oxygen and produces CO2!");
}
};
// Calling the implemented method
fire.combustion();
}
}
On running the above code, it will display the following output:
Fire needs Oxygen and produces CO2!