Tuesday, March 3, 2015

Anonymous Classes

There are 2 different kinds of anonymous classes.
1. Plain Old Anonymous Inner Classes
2. Argument declared anonymous Inner Classes.

Plain Old Anonymous Inner Classes version has 2 more flavours.


1.a. Plain Old Anonymous Inner Classes  (Flavor One): Subclass type

    public class Animal {
void eat()
{
System.out.println("Animal eats");
}
}

public class Forest {

public static void main(String[] args)
{
Animal animal=new Animal(){
void eat()
{
System.out.println("Dog eats");
}
};

animal.eat();
}
}


Here animal is instance of anonymous class which has been extended from Animal class. Note that, only overriden method can be accessed from animal object as per polymorphism laws.

1.b. Plain Old Anonymous Inner Classes (Flavor Two): Interface type

public interface Eatable {

void eat();
}

public class Forest {

public static void main(String[] args)
{
Eatable eAnimal=new Eatable()
{
public void eat()
{
System.out.println("Animal can eat");
}
};
eAnimal.eat();
}
}

This type of anonymous inner class implements only one Interface.

2. Argument declared anonymous inner class

Suppose we have an interface

public interface Eatable {

void eat();
}

and a function that takes an object which type has implemented that interface.

void letsEat(Eatable man)
{
man.eat();
}

In that case, we can create a class and implementes that interface and then we can pass it to the function. The smart way is to use argument declared anonymous inner class.

public class Forest {

void letsEat(Eatable man)
{
man.eat();
}
public static void main(String[] args)
{
Forest forest=new Forest();
forest.letsEat(new Eatable(){
public void eat()
{
System.out.println("I wanna eat");
}
});
}
}

No comments:

Post a Comment