Java 8 Static Method References (static::method)
- schick09
- Mar 16, 2024
- 2 min read
Updated: Apr 25, 2024
Java 8 introduced method references as a special type of lambda expression. Think of them as a type of 'shorthand' you can use to reference existing methods to provide the function implementations for your functional interface implementation.
We will first take a look at static method implementation.
In this example, we will be creating a new Thread object (whose constructor takes a Runnable). Runnable is a functional interface, in the sense that it implements only one abstract method (which we must override). We will provide the functional implementation of that Runnable object. When the Thread starts, it will print a simple message to the console.
Our first static method example shows the 'longhand' way of providing a Runnable implementation to the new Thread object and overriding its single abstract method by using an anonymous inner class. We are just showing this to show you the old and rather clunky way of accomplishing what we will soon accomplish with a static method reference implementation that is much cleaner
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Old anonymous inner class way...");
}});
t2.start();
Next, we'll tighten this up a little bit by showing how to provide a Runnable implementation to the new Thread object by using a lambda expression to create an anonymous inner class and override its single abstract method:
Thread t2 = new Thread(()-> System.out.println("Lambda expression way...."));
t2.start();
Much better - but here is our final (and desired) state. Here we will use Java 8's method reference to provide the abstract method implementation (and anonymous inner class instantiation of the Runnable functional interface):
t2 = new Thread(StaticMethodExample::threadStatus);
t2.start();
Much nicer! Concise and easy to read.
Here's a link to our GitHub location to access this code example:

Comments