Given:



interface Rideable {

    Car getCar(String name);
}

class Car {

    private String name;

    public Car(String name) {
        this.name = name;
    }
}

Which code fragment creates an instance of Car?

A.

Car auto = Car("MyCar")::new;
B.
Car auto = Car::new;
Car vehicle = auto::getCar("MyCar");
C.
Rideable rider = Car::new;
Car vehicle = rider.getCar("MyCar");
D.
Car vehicle = Rideable::new::getCar("MyCar");

題解

選項A,錯誤的用法。

選項B,錯誤的用法。Car並不是Function Interface,無法直接指派Lambda語法。

選項C,正確的用法。用Lambda語法來實作出Rideable介面的getCar方法,在這裡使用Lambda精簡語法的方式省略了以下匿名類別程式:

Rideable rider = new Rideable() {
    @Override
    public Car getCar(String name) {
        return new Car(name);
    }
};

或Lambda語法:

Rideable rider = name -> new Car(name);

如此一來,Rideable物件的getCar(String)方法就可以當作是new Car(String)來使用。

選項D,錯誤的用法。