Can an anonymous class have constructors in Java?



Anonymous Classes in Java are classes that do not have a name. They are typically used to extend a class or implement an interface without the need for a separate named class. The following are the common uses of anonymous classes:

  • Implementing event listeners.
  • Creating Runnable objects for threads.
  • Providing custom implementations for abstract methods of an abstract class.

Constructors in an Anonymous class

Anonymous classes cannot have a constructor, but the compiler provides a default constructor for them. This means that when you create an instance of an anonymous class, it will call the constructor of the superclass or the interface it implements.

Example

In the example below, we have an abstract class `Animal` with an abstract method 'sound()'. We create an anonymous class that extends 'Animal' and provides an implementation for the 'sound()' method. When we create an instance of this anonymous class, it implicitly calls the constructor of the 'Animal' class.

abstract class Animal {
   abstract void sound();
}

public class Main {
   public static void main(String[] args) {
      Animal dog = new Animal() {
         void sound() {
            System.out.println("Woof");
         }
      };
      dog.sound();
   }
}

When you run the above code, it will output:

Woof

In conclusion, while anonymous classes in Java do not have named constructors, they can still be instantiated and will call the constructor of their superclass or the interface they implement. This allows them to initialize their state without needing a separate constructor definition.

Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2025-08-08T15:39:51+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements