Monday, October 10, 2016

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:

Class (may be abstract or concrete).
Interface
Java anonymous inner class example using class

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();
 }
}

Internal working of given code

Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
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.
An object of Anonymous class is created that is referred by p reference variable of Person type.
Internal class generated by the compiler

import java.io.PrintStream;
static class TestAnonymousInner$1 extends Person
{
   TestAnonymousInner$1(){}
   void eat()
    {
        System.out.println("nice fruits");
    }
}
Java anonymous inner class example using interface

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();
 }
}


import java.io.PrintStream;
static class TestAnonymousInner1$1 implements Eatable
{
TestAnonymousInner1$1(){}
void eat(){System.out.println("nice fruits");}
}

No comments:

Post a Comment

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...