Java Program to demonstrate the anonymous interface.
Objective
Write a Java program to demonstrate an Anonymous Interface Implementation.
Algorithm / Approach
- In main, declare a
Runnable r = new Runnable() { ... };. - Inside the block, provide the concrete implementation for the abstract
run()method. - Write the countdown logic inside the run method.
- Pass the anonymous
Runnabledirectly into a new Thread:new Thread(r).start();.
Test.java
class Test {
public static void main(String[] a)
{
Runnable r= new Runnable(){
public void run() {
for(int i = 20; i>=0; i--) {
System.out.printf("%02d\r",i);
try {
Thread.sleep(1000);
}
catch(Exception e) { }
}
}
};
new Thread(r).start();
}
}
Explanation of the Program
- You cannot instantiate an interface (you can't say
new Runnable()). - However, the syntax
new Runnable() { ... }is NOT instantiating an interface. It is telling Java to silently create a brand new, unnamed class that *implements* Runnable, and immediately return an instance of that new class. - This was the standard way to handle callbacks and events in Java before Lambda Expressions were introduced in Java 8.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)