Supplier interface in java.util.function package in Java 8

In my previous posts I wrote about Predicate, Consumer and Function interfaces. In this post I will write about Supplier interface with which I will conclude the description of the interfaces in the java.util.function package. Though there are many other interfaces in that package, but the interfaces I have explained form the crux of the other interfaces.

The javadoc for Supplier interface states:

A supplier of objects. The result objects are either created during the invocation of get() or by some prior action.

And the sole method in this interface is get() which should return an object of the declared type.

To understand the usage of this interface, lets consider 2 classes- Vehicle and Car defined as:

class Vehicle{
  public void drive(){ 
    System.out.println("Driving vehicle ...");
  }
}
class Car extends Vehicle{
  @Override
  public void drive(){
    System.out.println("Driving car...");
  }
}

And lets consider a static method which invokes the drive() method on the instance of Vehicle or Car:

public class SupplierDemo {   
  static void driveVehicle(Supplier<? extends Vehicle> supplier){
    Vehicle vehicle = supplier.get();
    vehicle.drive();   
  }
}

And to invoke the above driveVehicle method, we should provide an implementation of the Supplier interface which we can do by passing in a lambda expression. Lets look at the code:

public static void main(String[] args) {
  //Using Lambda expression
  driveVehicle(()-> new Vehicle());
  driveVehicle(()-> new Car());
  
  //Using method expression
  driveVehicle(Vehicle::new);
  driveVehicle(Car::new);
}

The first two invocations are familiar to the readers of my blog, but the other two are something new and those are called as “Method Expression“. Soon I will write about method expression but if you are curious to know about it, you can read about it here under the section: “8. Method Expression“.

1 thought on “Supplier interface in java.util.function package in Java 8”

Leave a Reply

Discover more from Experiences Unlimited

Subscribe now to keep reading and get access to the full archive.

Continue reading