Java Program to Demonstrate the anonymous class.
Objective
Write a Java program to demonstrate an Anonymous Class extending another class.
Algorithm / Approach
- In the main method, declare a
Thread t = new Thread() { ... };. - Inside the curly braces immediately following the constructor, override the
run()method. - Write a countdown loop using
Thread.sleep()to create a timer. - 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
Threadon the fly. We don't bother giving this subclass a formal name (likeclass 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)