The inner class which is declared inside the body of a method is known as the local inner classes. The class declared inside the body of a method without naming it is known as anonymous inner classes.
The anonymous inner classes is very useful in some situation. For example consider a situation where you need to create the instance of an object without creating subclass of a class and also performing additional tasks such as method overloading.
A class that have no name is known as anonymous inner class.
Anonymous class can be created by:
Program of anonymous inner class by abstract class
abstract class Employee{
abstract void work();
}
class Manager{
public static void main(String args[]){
Employee emp = new Employee(){
void work()
{
System.out.println("Manage the team");}
};
emp.work();
}
}
Output:
After compiling we will get the following class files.
The internal code generated by the compiler for annonymous inner class
import java.io.PrintStream;
static class Manager$1 extends Employee
{
Manager$1(){
}
void work()
{
System.out.println("Manage the team");
}
}
Program of anonymous inner class by interface:
interface Employee{
void work();
}
class Manager{
public static void main(String args[]){
Employee emp = new Employee(){
void work()
{
System.out.println("Manage the team");}
};
emp.work();
}
}
Output:
The internal code generated by the compiler for annonymous inner class
import java.io.PrintStream;
static class Manager$1 implements Employee
{
Manager$1(){
}
void work()
{
System.out.println("Manage the team");
}
}
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…