Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Create a Class Without a Name in Java



Yes, we can create a class without a name in Java using the anonymous class. It is a type of inner class which does not have a name and whose instance is created at the time of the creation of the class itself. You can create this class in a single statement using the new keyword. Creating multiple instances of this class is not allowed.

You can use anonymous classes in case where you need to override methods of a class or an interface for a one-time use, and you don't want to create a separate named class for it.

Creating Anonymous Class in Java

You can create a class without a name (Anonymous class) in Java by using the following ways:

  • Extending Class
  • Implementing Interface

Anonymous Class by extending another Class

A class without a name can be created by extending another class. It is used to modify or extend the behavior of an existing class without creating a subclass.

Syntax

The syntax to create an anonymous inner class by extending another class is as follows:

Class objectName = new Class() {
    // Override necessary methods
};

Example

Let's see an example program:

public class Anonymous {
   public void show() {}
   public static void main(String args[]) {
      Anonymous a = new Anonymous() {
         public void show() {
            System.out.println("Anonymous Class");
         }
      };
      a.show();
   }
}

Output of the above Java code:

Anonymous Class

Anonymous Class by implementing Interface

An Interface is a type of class that is defined using the keyword interface. To access its members within a class, we need to use the implements keyword while defining that class.

To create an anonymous class, you can implement the interface and override its methods without creating a separate named class.

Syntax

Use the syntax given below to create an anonymous class by implementing an interface:

Interface objectName = new Interface() {
    // Override necessary methods
};

Example

In the following Java program, we create an anonymous class using an interface and, print its output statement:

// Library interface
interface Library {
   void displayBook();
}
public class Student {
   public static void main(String[] args) {
      // anonymous class
      Library book = new Library() {
         @Override
         public void displayBook() {
            System.out.println("Books are stored in library!");
         }
      };
      // method call
      book.displayBook();
   }
}

On running the above code, it will display the following output:

Books are stored in library!
Updated on: 2025-05-16T15:51:21+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements