Search code examples
javainterfacelambdarunnable

Can you implement an interface during initialization?


I was reading through one of Oracle's lambda expression tutorials, and came across the following code:

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html

public class RunnableTest {
  public static void main(String[] args) {

  System.out.println("=== RunnableTest ===");

  // Anonymous Runnable
  Runnable r1 = new Runnable(){

    @Override
    public void run(){
      System.out.println("Hello world one!");
    }
  };

  // Lambda Runnable
  Runnable r2 = () -> System.out.println("Hello world two!");

  // Run em!
  r1.run();
  r2.run();
  }
}

My question is why didn't they implement Runnable when creating the class? Since they overrode the run method when initializing r1, did that take care of the implementation?


Solution

  • Yes, this is called an anonymous class in Java.

    https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

    You can implement an interface or extend a class when using the new operator, which will create a new instance of the unnamed subclass you define at the time. It's mostly used when you're writing code to be used in another thread or as a callback, since you only get the one instance.

    The new lambda syntax in Java 8 replaces anonymous classes for interfaces with a single method, such as Runnable or the interfaces in java.util.function. This is what they're demonstrating in the example.