Sobes.tech
Junior

What are anonymous classes and where are they used?

sobes.tech AI

Answer from AI

An anonymous class is an inner class without a name. It is declared and instantiated simultaneously. It is used when you need to create a one-time object of a class that implements an interface or extends another class. It is most commonly used for:

  • Event handlers: In Swing or JavaFX for creating listeners.
  • Interface implementations: When a simple, one-time object implementing a single method of an interface is needed.
  • Creating threads: For implementing Runnable.

Example of creating an anonymous class implementing the Runnable interface:

// Implementation of the Runnable interface using an anonymous class
Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello from anonymous runnable!");
    }
};

Example of creating an anonymous class extending the Thread class:

// Extending the Thread class using an anonymous class
Thread myThread = new Thread() {
    @Override
    public void run() {
        System.out.println("Hello from anonymous thread!");
    }
};

Anonymous classes have access to final or effectively final local variables of the outer scope.

Main restrictions:

  • Cannot have an explicit constructor (the constructor is called implicitly during creation).
  • Cannot declare static members.
  • Cannot inherit from or implement more than one class/interface respectively.
What are anonymous classes and where are they used… - sobes.tech