Java Anonymous inner class

A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways:

  1. Class (may be abstract or concrete).
  2. Interface

Anonymous inner class using class

Example
snippet
abstract class Person{
  abstract void eat();
}
class TestAnonymousInner{
 public static void main(String args[]){
  Person p=new Person(){
  void eat(){System.out.println("nice fruits");}
  };
  p.eat();
 }
}
Output
nice fruits

Internal working of given code

Example
snippet
Person p=new Person(){
  void eat(){System.out.println("nice fruits");}
  };
  1. A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.
  2. An object of Anonymous class is created that is referred by p reference variable of Person type.

Internal class generated by the compiler

Example
snippet
import java.io.PrintStream;
static class TestAnonymousInner$1 extends Person
{
   TestAnonymousInner$1(){}
   void eat()
    {
        System.out.println("nice fruits");
    }
}

Anonymous inner class using interface

Example
snippet
interface Eatable{
 void eat();
}
class TestAnnonymousInner1{
 public static void main(String args[]){
 Eatable e=new Eatable(){
  public void eat(){System.out.println("nice fruits");}
 };
 e.eat();
 }
}
Output
nice fruits

Internal working of given code

It performs two main tasks behind this code:

Example
snippet
Eatable p=new Eatable(){
  void eat(){System.out.println("nice fruits");}
  };
  1. A class is created but its name is decided by the compiler which implements the Eatable interface and provides the implementation of the eat() method.
  2. An object of Anonymous class is created that is referred by p reference variable of Eatable type.

Internal class generated by the compiler

Example
snippet
import java.io.PrintStream;
static class TestAnonymousInner1$1 implements Eatable
{
TestAnonymousInner1$1(){}
void eat(){System.out.println("nice fruits");}
}
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +