Java/J2EE and SOA (325 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (41 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (324 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

How to Implement Anonymous Class in Java

Published on Aug 29,2019 14 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

Anonymous classes let you write small code and let you declare and instantiate class at the same time. These classes do not have names, it is used when you want to use any class only once. It is an important aspect of Java Programming. Let’s understand what is Anonymous Class in Java in the following order:

 

Declaring Anonymous Classes

Normally we create a class i.e we declare class but, anonymous classes are expressions which means that we define the anonymous class in another expression. In simple words, the anonymous inner class is a class without names and only one object is created.

Anonymous-Class-In-Java

Anonymous class is useful when we have to create an instance of the object with overloading methods of a class or interface without creating a subclass of class.

Anonymous can be created in two ways:

  • Class(can also be Abstract)
  • Interface

In the anonymous class we can declare the following:

  • Fields
  • Extra methods
  • Instance Initializers
  • Local classes

 

Syntax of Anonymous Class in Java

The syntax of an anonymous class is just like constructor except that there is a class definition in the block as shown in the snippet below:

// AnonymousClass = interface,abstract/concrete class.
AnonymousClass t = new AnonymousClass()
{
  // methods and fields
  public void someMethod()
  {
     //code goes here
   }  
}

Let’s take a look at the following example:

The following example, HelloAnonymousClass, uses anonymous classes in the initialization statements of the local variables greetSomeone but, uses a local class for the initialization of the variable greetWorld:

public class HelloAnonymousClass {
interface HelloWorld {
public void sayHello();
public void sayHelloTo(String someone);
}
public void sayHello() {
class GreetWorld implements HelloWorld {
String name = "world";
public void sayHello() {
sayHelloTo("world");
}
public void sayHelloTo(String someone) {
name = someone;
System.out.println("Hello " + name);
}
}
HelloWorld greetWorld = new GreetWorld();
HelloWorld greetSomeone = new HelloWorld() {
String name = "jon";
public void sayHello() {
sayHelloTo("Jon");
}
public void sayHelloTo(String someone) {
name = someone;
System.out.println("hola " + name);
}
};
greetWorld.sayHello();
greetSomeone.sayHelloTo("Doe");
}
public static void main(String... args) {
HelloAnonymousClass myApp = new HelloAnonymousClass();
myApp.sayHello();
}
}

As we have seen that anonymous class is an expression the syntax is just like constructor except there is a class definition in the block. Consider the instantiation of the greetSomeone object:

HelloWorld greetSomeone = new HelloWorld() {
String name = "jon";
public void sayHello() {
sayHelloTo("Jon");
}
public void sayHelloTo(String someone) {
name = someone;
System.out.println("hola " + name);
}
}

The anonymous class is composed of the following:

  • new operator.
  • It can implement an interface or extend a class. As in above example, it is implementing the interface.
  • It contains parentheses just like normal classes in order to pass arguments to the constructor.
  • Contains body which contains method declarations. Declarations are not allowed.

Anonymous class should be part of statements.

In the above example, the anonymous class expression is part of the statement which is initiated by greetSomeone.

 

Ways to Create Anonymous Class in Java

There are 3 ways to create Inner Class in Java

  • By Extending Class

We can create an anonymous inner class by extending other class, suppose we have to create a thread by using Thread class we can create an anonymous inner class instead of creating a separate class.

//Program to illustrate Anonymous Inner class by extending other class
class AnonymousThreadClass {
public static void main(String[] args) {
//Anonymous Inner class that extends Thread class
Thread t = new Thread() {
public void run() {
System.out.println("Child!");
}
};
t.start();
System.out.println("Parent!");
}
}

Output:

Parent!

Child!

 

  • By Implementing Interface

We can also create an anonymous inner class by implementing the interface. Now, as we created an inner class by extending class similarly we can create a class that implements an interface.

//Program to illustrate Anonymous Inner class by implementing interface
class AnonymousThreadClass
{
public static void main(String[] args)
{
//Anonymous Inner class that implements interface
Runnable r = new Runnable()
{
public void run()
{
System.out.println("Child!");
}
};
Thread t = new Thread(r);
t.start();
System.out.println("Parent!");
}
}

Output:

Parent!

Child!

 

  • As an argument to a Method/Constructor

To understand syntax lets look at the example below:

//Program to illustrate Anonymous Inner class by argument
class AnonymousThreadClass {
public static void main(String[] args) {
//Anonymous class with constructor argument
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println("Child!");
}
});
t.start();
System.out.println("Parent!");
}
}

Output:

Parent!

Child!

 

Difference Between Regular and Anonymous Inner Class

  • We can implement multiple numbers of interfaces by using normal class but, with an anonymous inner class, we can only implement one interface.

  • With regular class we can extend a class and also implement multiple interfaces but, with an anonymous inner class, we can either extend a class or implement an interface but not both at the same time.

  • With anonymous we cannot write constructor because the anonymous inner class does not have name and name of the constructor should be same as the class name.

 

In this article, we saw what is an anonymous inner class and how can we create one. we went through the syntax of anonymous inner class and also how we can create an anonymous class in 3 ways and with this, we come to an end of this Anonymous Class in Java article. Check out the Java training by Edureka.

Got a Question? Mention it in the Comment Section of this article and we will get back to you as soon as possible.

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.