< Prev
Next >



Anonymous Inner Class



Anonymous Inner class is an inner class that is declared without any class name and that's why it's called anonymous. You can define an anonymous inner within a method or even within an argument to a method.

Anonymous class can be used to -

Anonymous class extending an existing class and overriding its method -:

Here we have a class, Food, with its method cook(). We have another class B, in which we have one instance variable of type Food, named - pasta. This instance variable, pasta, doesn't refer to the instance of Food but it refers to an instance of anonymous inner class which is has extended class, Food and has overridden it's cook() method.
//Defining anonymous class within a method
 
 public class Food
{

public void cook()
{
System.out.println("Cooking food");
}

}

class B
{
Food pasta = new Food() {	//Anonymous class definition starts
	public void cook()	//overriding cook() method of Food class in this Anonymous class.
	{
		System.out.println("Cooking Pasta");
	}
	
	};			//Anonymous class defintion ends, semicolon is very important


public static void main(String... ar)
{
B ob = new B();
ob.pasta.cook();
}

}


Output is - :

Cooking Pasta

Program Analysis




Anonymous class implementing an interface and its method -:

Here we have an interface, Food, with its method cook(). We have another class B, in which we have one instance variable of type Food, named - pasta. This instance variable, pasta, doesn't refer to the instance of Food but it refers to an instance of anonymous inner class which has implemented interface, Food and has implemented it's cook() method.
interface Food
{

public void cook();

}

class B
{
Food pasta = new Food() { //Anonymous inner class begins
	public void cook()
	{
		System.out.println("Cooking Pasta");
	}
	
	};	//Anonymous class defintion ends, semicolon is very important


public static void main(String... ar)
{
B ob = new B();
ob.pasta.cook();
}

}

Output is -:

Cooking pasta

Program Analysis




Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter



< Prev
Next >
< Static Nested Class
Scanner Class >
Please subscribe for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
JSP & Servlets

Ad2