Advertisement



< 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 class 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 has extended class Food and has overridden its 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





Advertisement




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 its 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 -




< Prev
Next >
< Static Nested Class
Scanner Class >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement