Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the anonymous interface.

Java Code Example — Inner Class Programs

ADVERTISEMENT

Java Program to demonstrate the anonymous interface.

Objective

Write a Java program to demonstrate an Anonymous Interface Implementation.

Algorithm / Approach

  1. In main, declare a Runnable r = new Runnable() { ... };.
  2. Inside the block, provide the concrete implementation for the abstract run() method.
  3. Write the countdown logic inside the run method.
  4. Pass the anonymous Runnable directly 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)
ADVERTISEMENT