Difference between Anonymous object and anonymous class

Below is an example of Anonymous object.
Anonymous object is an object without name. Generally anonymous object is used when only one method need to be invoked with the object, and invoking methods with the created object may not be further required in the program.

class InnerDemo
{
	void show(){
		System.out.println("show() in InnerDemo class");
	}
}

public class AnonymounsInnerClassObject {
	public static void main(String args[])
	{
		new InnerDemo().show();
	}
}

Anonymous Inner class is a class which does not have name, however there are some constraints like explicit constructor cannot be used with Anonymous Inner class.

Anonymous object or named object can be created using an Anonymous class.

Below is an example of creating Anonymous object of Anonymous class.

class InnerClass{

	public void met1()
	{
		System.out.println("met1() in InnerClass");
	}
}

public class AnonymousObj1 {
	public static void main(String args[])
	{
		new InnerClass(){
			public void met1(){
				System.out.println("met1() in Anonymous class");
			}
		}.met1();
	}
}

Below is an example of creating named object of Anonymous class.

class InnerClass1{

	public void met1()
	{
		System.out.println("met1() in InnerClass1");
	}
}

public class NamedObj {
	public static void main(String args[])
	{
		InnerClass1 obj = new InnerClass1(){
			public void met1(){
				System.out.println("met1() in Anonymous class");
			}
		};

		obj.met1();
	}
}

You may also like to read:
What is static inner class?
Create Thread by extending anonymous class from Thread class
What is inner interface?

Leave a Reply