Reading about the new Supplier
interface I can't see any advantage of its usage.
We can see bellow an example of it.
class Vehicle{
public void drive(){
System.out.println("Driving vehicle ...");
}
}
class Car extends Vehicle{
@Override
public void drive(){
System.out.println("Driving car...");
}
}
public class SupplierDemo {
static void driveVehicle(Supplier<? extends Vehicle> supplier){
Vehicle vehicle = supplier.get();
vehicle.drive();
}
}
public static void main(String[] args) {
//Using Lambda expression
driveVehicle(()-> new Vehicle());
driveVehicle(()-> new Car());
}
As we can see in that example, the driveVehicle
method expects a Supplier
as argument.
Why don't we just change it to expect a Vehicle
?
public class SupplierDemo {
static void driveVehicle(Vehicle vehicle){
vehicle.drive();
}
}
public static void main(String[] args) {
//Using Lambda expression
driveVehicle(new Vehicle());
driveVehicle(new Car());
}
What is the advantage of using Supplier
?
EDIT: The answers on the question Java 8 Supplier & Consumer explanation for the layperson doesn't explain the benefits of using Supplier
.
There is a comment asking about it, but it wasn't answered.
What is the benefit of this rather than calling the method directly? Is it because the Supplier can act like an intermediary and hand off that "return" value?
In your example above I'd not use a supplier. You are taking a Vehicle
to drive, not requesting vehicles.
However to answer your general question:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With