PostHeaderIcon Java Annonymous Inner Class Example

public class AnonymousInnerClass
{
private int testVariable1 = 1;

Fruit f1 = new Fruit() //Class must extend Fruit. It is not of type Fruit. It is a Polymorphic reference.
{
public void eat()
{
System.out.println(“Eat a bannana”);
System.out.println(“Test variable 1 is: “+testVariable1);
}

/*public void getColour() //Cannot do this because no getColour is Fruit class
{
System.out.println(“Colour is yellow!);
} */
};

public void eatFood()
{
f1.eat();
}

public static void main (String args[])
{
AnonymousInnerClass a1 = new AnonymousInnerClass();
a1.eatFood();
a1.f1.eat(); //You can do this.
}
}

class Fruit
{
public void eat()
{
System.out.println(“Eat fruit”);
}
}

Leave a Reply

You must be logged in to post a comment.

Adsense