I would like to ask about the following piece of code related to Functional Interfaces. I am confused by:
Rideable rider = Car :: new
Is it creating a Rideable
(interface) or Car
(class) instance?
If it is creating a Car
object, the constructor new Car()
(i.e. with no arguments) should be not existing, then how come this can be valid?
I Have been reading through this tutorial ,but still could not figure it out.
@FunctionalInterface
interface Rideable {
Car getCar (String name);
}
class Car {
private String name;
public Car (String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
Rideable rider = Car :: new;
Car vehicle = rider.getCar("MyCar");
}
}
You are using the Lambda syntax to implement the getCar()
method of the Rideable interface, where the following anonymous class program is omitted using Lambda's concise syntax:
Rideable rideable = new Rideable() {
@Override
public Car getCar(String name) {
return new Car(name);
}
};
This is Java 7 code. You can achieve the same thing using using Lambda expression:
Rideable rider = name -> new Car(name);
Or as in your example, using method reference:
Rideable rider = Car::new;
As a result, the getCar(String)
method of the Rideable object can be used as a new Car(String)
.
And as an answer to your question, you are creating an instance of Car
class that implements the Rideable interface. This is another way you can implement an interface without using implement
keyword.
If you are thinking of:
Car auto = Car("MyCar")::new;
or
Car auto = Car::new;
Car vehicle = auto::getCar("MyCar");
or
Car vehicle = Rideable::new::getCar("MyCar");
All these examples are wrong
approaches. I gave you this examples because these are common mistakes that can be made when we are speaking about Lambda expressions or method reference.