Let's create and run some Runnable
! With Java 8, instead of using anonymous classes, we can use lambda expressions.
The syntax (params) -> statement
can be used to create an instance of Runnable by implementing its run
method.
This is possible only for interfaces that have only one abstract method, and such interfaces are called functional interfaces.
Starting from Java 8, interface methods don't have to be abstract. Java 8 introduced default methods, which are interface methods that have a body.
Before Java 8, we had to write code like this:
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello!");
}
};
r.run();
With Java 8 and later Java versions, we can use lambda expressions:
Runnable r = () -> System.out.println("Hello!");
r.run(); // prints "Hello!"