Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to Demonstrate the anonymous class.

Java Code Example — Inner Class Programs

ADVERTISEMENT

Java Program to Demonstrate the anonymous class.

Objective

Write a Java program to demonstrate an Anonymous Class extending another class.

Algorithm / Approach

  1. In the main method, declare a Thread t = new Thread() { ... };.
  2. Inside the curly braces immediately following the constructor, override the run() method.
  3. Write a countdown loop using Thread.sleep() to create a timer.
  4. Call t.start().
Test.java
class Test {
 public static void main(String[] a)
 {
  Thread t= new Thread(){ 
   public void run() {
    for(int i = 20; i>=0; i--)  { 
     System.out.printf("%02d\r",i);
     try {
      Thread.sleep(1000);
     }
     catch(Exception e) { }
    }
   }
  };
  t.start();
 }
}

Explanation of the Program

  • An Anonymous Class is an inner class without a name. It is declared and instantiated in a single expression.
  • In this program, we are creating a subclass of Thread on the fly. We don't bother giving this subclass a formal name (like class MyCountdownThread extends Thread) because we are only going to use it exactly once right here.
  • This drastically reduces boilerplate code, especially for simple, one-off event handlers or background tasks.

Complexity

Time Complexity O(n) - Loop execution.
Space Complexity O(1)
ADVERTISEMENT