Explaining Anonymous Inner Class in Java with Examples

by

Posted on 19 December 2017

Anonymous class is a type of inner class or nested class which do not have any name, it is mainly used to override methods of a class or an interface, an anonymous class can be created using two methods:

  • Abstract Classes
  • Interfaces

Let us see a simple example based on Java Interface.

interface X{
	void inc();
}

class MyClass implements X{
	public void inc(){
		System.out.println("This is inc method");
	}
}

class Interface{
	public static void main(String args[]){
		MyClass obj = new MyClass();
		obj.inc();
	}
}

In the above example we created a simple interface name X and implemented it in a class named MyClass, method inc() contains its body in class MyClass and has been called in the main method using object obj.

Now let’s see the same example using Anonymous class.

interface X{
	void inc();
}

class anon{
	public static void main(String[] args){
		X x = new X(){
			@Override
			public void inc(){
				System.out.println("This is inc() method");			
			}
		};
		x.inc();
	}
}

In the above example, instead of creating a separate class and defining the method body in it we used the Interface name and created an Anonymous class having the method body in it and we called the method using the Interface object.

What if we want to use a single method two or more times but for different purposes and without declaring their bodies again and again in different classes. Let’s see another example to clear the idea about Anonymous Classes.

interface X{
	int squareAndCube(int x);
}

class anon{
	public static void main(String[] args){
		X obj1 = new X(){
			@Override
			public int squareAndCube(int x){
				return (x*x);			
			}
		};
		X obj2 = new X(){
			@Override
			public int squareAndCube(int x){
				return (x*x*x);			
			}
		};
		int square = obj1.squareAndCube(2);
		int cube = obj2.squareAndCube(2);
		System.out.println("Square is : "+square+"\n"+"Cube is : "+cube);
	}
}

Output:

Java Anonymous inner classes program

Excercise: Try doing the same example using an abstract class instead of using an Interface.

Hint :

abstract class X{
	abstract int squareAndCube(int x);
}

class anon{
	public static void main(String[] args){
		X obj1 = new X(){
			@Override
			public int squareAndCube(int x){
				return (x*x);			
			}
		};
		int square = obj1.squareAndCube(2);
		System.out.println("Square is : "+square);
	}
}

Try adding the method body for cube using an abstract class in the above example.


If You Love this article, You Should Consider:

  • Like us on Facebook
  • Follow us on Instagram
  • Follow us on Twitter
  • Subscribe to our Newsletter.
  • Let us know your suggestions and queries in the comments below.

Thank you for your Love and Support

Share your thoughts

Search
Adverstisement
Adverstisement