I have been in the software development industry since 2010, working on enterprise product development using ADF. I am usually keen on learning about software design and emerging technologies. You can find me hanging around in the JavaRanch Forums where I am one of the moderators. Apart from Java, I am fascinated by the ease of use and simplicity of Ruby and Rails. Mohamed is a DZone MVB and is not an employee of DZone and has posted 58 posts at DZone. You can read more from them at their website. View Full User Profile

Supplier Interface in java.util.function Package in Java 8

  • submit to reddit

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{
  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();

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

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“.


Published at DZone with permission of Mohamed Sanaulla, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)