Annonymous inner class in java

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

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:
  1. Class (may be abstract class also).
  2. Interface
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.
  • Employee.class
  • Manager$1.class
  • Manager.class
  1. A class is created but its name is decided by the compiler which extends the Employee class and provides the implementation of the work() method.
  2. An object of Anonymous class is created that is referred by emp reference variable of Employee type. As you know well that Parent class reference variable can refer the object of Child class.
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");
    }
}



<<Previous <<   || Index ||   >>Next >>

No comments:

Post a Comment