Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Nested classes
3.
Introduction to Anonymous Class in Java
4.
Syntax of Anonymous Class in Java
5.
Syntax of Anonymous Class in Java
6.
Anonymous Class In Java Extending a Class
6.1.
Implementation
6.1.1.
Output
6.2.
Explanation
7.
Anonymous Class In Java Implementing an Interface
7.1.
Implementation
7.1.1.
Output
7.2.
Explanation
8.
Difference Between Normal class and Anonymous class
9.
Properties of Anonymous class in Java
10.
Use Case of Anonymous class in Java
10.1.
Event Listeners UI
10.2.
Runnable Threads
11.
Advantages of Anonymous class in Java
12.
Disadvantages of Anonymous class in Java
13.
Frequently Asked Questions
13.1.
Can an anonymous class in Java have constructors?
13.2.
When should we use an anonymous class instead of a named class?
13.3.
What is an anonymous class and how do you create it in Java?
13.4.
What are some of the things to keep in mind when you are using Anonymous classes?
13.5.
Can an Anonymous class implement multiple interfaces in Java?
14.
Conclusion
Last Updated: Mar 27, 2024

Anonymous Class In Java

Author Vidhi Sareen
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Java is one of the most popular programming nowadays. Java supports many built-in functions that support anonymous classes. An anonymous object in Java is defined to create an object without any reference variable. Anonymous classes are most commonly used to implement a class or interface without creating a new named class. In this article, we will discuss anonymous classes in Java.

Anonymous Class In Java

We will discuss different aspects like use cases, advantages, and disadvantages of anonymous classes in Java.

Nested classes

To learn more about Anonymous Class in Java, we must know what Nested classes are and how Anonymous classes are connected to Nested classes. 

nested class

A Nested class is a class that is declared inside another class or interface. A nested class is used to combine certain classes that will help in reading and modifying the code.

Nested classes are divided into Static Nested and Non-Static nested classes. The Inner Class Non-Static nested classes are further divided into Member Inner, Local, and Anonymous classes. The Anonymous class is a subset of the Nested class.

Also see, Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Introduction to Anonymous Class in Java

In Java, Anonymous Class is an inner class declared without a name. Since they don't have names, we can not use them to create anonymous class instances. It just works the same as that of the local class. We can declare Property(Fields), Methods, or local classes inside an anonymous class. It is always recommended to use an anonymous class if you have to override the methods of a class or an interface. An anonymous class must be defined inside another class. 

anonymous class in java

Syntax of Anonymous Class in Java

//defining anonymous class
new TypeName()
{
// body of the anonymous class
};


'TypeName' is the name of the class or an interface that the anonymous class extends or implements. The anonymous body class consists of methods or fields. The semicolon at the end indicates that the expression is written inside a class method.

We can create an anonymous class in Java in two ways. They are as follows:

The syntax and concept of anonymous class in Java will be more clear from the examples below. We will discuss cases where an anonymous class is extending a class and implementing an interface.

Syntax of Anonymous Class in Java

Anonymous classes in Java are classes without a name that are both declared and instantiated in a single line of code. They're commonly used when you want to use a local class only once. While they don't have a named identity, they have a type which is either a class type, or an interface type.

Here's the general syntax for an anonymous class that extends a class:

new ClassName() {
   // class body
};

And here's the general syntax for an anonymous class that implements an interface:

new InterfaceName() {
   // class body
};

Here's an example of each. First, extending a class:

abstract class AbstractClass {
   abstract void doSomething();
}
// somewhere in code
AbstractClass instance = new AbstractClass() {
   @Override
   void doSomething() {
       System.out.println("Doing something.");
   }
};
instance.doSomething();

And implementing an interface:

interface Interface {
   void doSomething();
}
// somewhere in code
Interface instance = new Interface() {
   @Override
   public void doSomething() {
       System.out.println("Doing something.");
   }
};
instance.doSomething();

In both examples, the method doSomething() is overridden from either the abstract class or the interface. The instance is then used to call that method.

Note that you can only create anonymous classes for interfaces or for classes that have a public or default constructor. If a class has only private constructors, you cannot create an anonymous class for it.

Anonymous Class In Java Extending a Class

Till Now we have discussed what Anonymous classes are. Now, we will discuss how Anonymous class is extended from a Class with the help of an example.

anonymous class in java extending a class

 

Let's look at the code below and try to understand how anonymous is been extended from another class.

Implementation

class Anonymous_Demo_Class {
   
//this method creates an anonymous class that extends the 'department' class
    public void newClass() {

      // anonymous class extending 'Department' class
      Department d1 = new Department() {

        //Override the 'show' method
         @Override
         public void show() {
            System. out.println("Inside an anonymous class.");
         }
      };
      d1.show();
   }
}

class Department {
   public void show() {
      System. out.println("Inside the department class");
   }
}

class Main {
   public static void main(String[] args) {

       //creates an instance
       Anonymous_Demo_Class demo = new Anonymous_Demo_Class();
       demo.newClass();
   }
}

Output

Output

Explanation

In this example, the 'Anonymous_Demo_Class()' class defines a method called 'newClass().' This method creates an anonymous class that extends the 'Department' class. This anonymous class overrides the 'show' method and prints a different output than the original. 

Anonymous Class In Java Implementing an Interface

Till Now we have discussed what Anonymous classes in Java  are and how we can extend anonymous class from another class. Now, we will discuss how Anonymous class is implemented from an interface with the help of an example.

anonymous class in java implementing an interface

Let's look at the code below and try to understand how an anonymous class is implemented from an interface.

Implementation

class Anonymous_Demo_class {

   //This method creates an anonymous class that extends the 'department' interface
   public void newClass() {

      // anonymous class extending 'Department' interface
      Department d1 = new Department() {

         //Override the 'show' method
         @Override
         public void show() {
            System. out.println("Inside an anonymous class.");
         }
      };
      d1.show();
   }
}

interface Department {
   public void show();
}

class Main {
   public static void main(String[] args) {

      //creates an instance
      Anonymous_Demo_class demo = new Anonymous_Demo_class();
      demo.newClass();
   }
}

Output

Output

Explanation

This code creates an anonymous class that implements the 'Department' interface and overrides the show method. In the main method, we have made an instance of 'Anonymous_Demo_class' and called the new class Method.

Difference Between Normal class and Anonymous class

The main difference between a normal class and an Anonymous class in Java are:

Normal Class Anonymous Class
It requires a name It does not require any name
Used to create objects that will be used multiple times Used to create objects that will be used only once
It can be accessed anywhere in the code They can only be accessed within a box of code where they are defined
It can be private, protected, or public It can only be public
It can be used anywhere in the program They can be used where they have defined

Properties of Anonymous class in Java

  • Anonymous classes are declared without a name.
     
  • Anonymous classes are declared without a name.
     
  • Anonymous classes are named inner classes and defined inside another class or method.
     
  • Anonymous classes are used to create objects once.
     
  • Anonymous classes can be only inherited from one class or implemented by one interface.
     
  • Anonymous classes cannot have a constructor but have an alternative option known as an instance initializer to initialize their state.

Use Case of Anonymous class in Java

Now, let’s discuss some of the use cases where anonymous classes are used.

Event Listeners UI

They are primarily used in Graphic User Interface programming. Here the most common use case is used to create multiple event listeners. For example, we need to instantiate an interface to a given functionality to a button in the UI. But we can only instantiate it indirectly. So, in this case, we used an anonymous class. This will give a very concise code.

Runnable Threads

Anonymous class in Java is used to create a thread only once. We can create a named class for this, but it can override it again if you want to create a thread once. For example let's take this sample code.
 

new Thread(new Runnable(){
//override
public void run(){
System. out. println(“Coding Ninja”);
}
}).start();


In this code, the anonymous class implements the Runnable interface, and the run() method is called when the thread starts.

Advantages of Anonymous class in Java

There are many advantages to using Anonymous Class in Java. Below are some of the main advantages that made Anonymous class so popular.

  • Anonymous classes in Java give a short piece of code that is easy to read, understand, and modify.
     
  • Anonymous classes in Java can be very versatile, meaning they can be implemented by interface or extend a class.
     
  • Anonymous classes in Java can create a listener for an event.
     
  • Anonymous classes in Java can be used to avoid creating a new class file. Thus it makes a positive impact on the storage.
     
  • Anonymous classes in Java can be used to make the code more manageable and maintainable.

Disadvantages of Anonymous class in Java

Although the Anonymous class have so many advantages, there are some limitations that make the Anonymous class not so efficient for the use cases. 

  • They are tough to debug when used in complex programming.
     
  • Overusing anonymous classes in a code might make it difficult to read and understand.
     
  • It can also create duplicates if they are repeatedly used in the code. 
     
  • It creates problems in testing. It becomes more challenging to test a code if there are multiple anonymous classes.

Frequently Asked Questions

Can an anonymous class in Java have constructors?

Anonymous classes in Java cannot have an explicit constructor. They can use the parent class's constructor or interface from which they are extending or implementing.

When should we use an anonymous class instead of a named class?

The anonymous class should be used when you need to define a class that needs to be used only once or when the content of the functionality is closely related to each other.

What is an anonymous class and how do you create it in Java?

An anonymous class in Java is an unnamed class defined and instantiated in a single statement. It's created using the 'new' keyword, followed by class/interface type, and then enclosing the class body within braces {}.

What are some of the things to keep in mind when you are using Anonymous classes?

Anonymous classes are less efficient than that of the named classes. They can create problems to read and understand when they are complex. It also causes issues in maintaining or debugging.

Can an Anonymous class implement multiple interfaces in Java?

It cannot have multiple interfaces in Java because they are related to names. An anonymous class can only implement one interface in Java.  

Conclusion

An anonymous class in Java is a way to create a class without explicitly defining its name. Anonymous classes are used when you want to implement an interface or extend a class. There are many advantages of using anonymous classes like it helps in simplifying the structure of the code and makes it more understandable and easy to modify. However, there are some disadvantages or drawbacks of using anonymous classes, like it makes the code difficult to debug or test; or it may create duplicates in the code.  

To learn more about such topics, check out the link below:

You can find more informative articles or blogs on our platform. You can also practice more coding problems and prepare for interview questions from well-known companies on your platform, Coding Ninjas Studio.

Previous article
Classes and Objects in Java
Next article
Abstract Class in Java
Live masterclass