dsa

Java Anonymous Class

In this tutorial, you will learn about anonymous classes in Java with the help of examples.

Anonymous Class

It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overloading methods of a class or interface, without having to actually subclass a class.

Syntax :


// TestClass can be interface,abstract/concrete class.
TestClass t = new TestClass() 
{
   	// data members and methods
   	public void testMethod() 
   	{
      		........
      		........
    	}   
};

Anonymous Class Extending a Class


class City
{
   	public void display() 
	{
      		System.out.println("Inside the City class");
   	}
}

class AnonymousClass 
{
   	public void createClass() 
	{

      		// creation of anonymous class extending class Polygon
      		City c1 = new City() 
		{
         		public void display() 
			{
            			System.out.println("Inside an anonymous class.");
         		}
      		};
      		c1.display();
   	}
}

class Main 
{
   	public static void main(String[] args) 
	{
       		AnonymousClass an = new AnonymousClass();
       		an.createClass();
   	}
}

Output :

Inside an anonymous class.

Anonymous Class Implementing an Interface


interface City
{
   	public void display();
}

class AnonymousClass 
{
   	public void createClass() 
	{

      		// creation of anonymous class extending class Polygon
      		City c1 = new City() 
		{
         		public void display() 
			{
            			System.out.println("Inside an anonymous class.");
         		}
      		};
      		c1.display();
   	}
}

class Main 
{
   	public static void main(String[] args) 
	{
       		AnonymousClass an = new AnonymousClass();
       		an.createClass();
   	}
}

Output :

Inside an anonymous class.