
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.