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