# method & constructor Reference

在Java 8中，引入了方法引用（Method Reference）和构造器引用（Constructor Reference）这两个特性，它们用于简化Lambda表达式，使代码更加清晰易读。

#### 方法引用（Method Reference）：

方法引用允许您直接引用现有的方法作为Lambda表达式的替代。语法为`類名::方法名`，或者是`實例::方法名`，有以下幾種情況：

1. **靜態方法引用**：使用類名和方法名引用靜態方法。例如：`類名::靜態方法名`。
2. **實例方法引用**：使用對象實例的方法名引用實例方法。例如：`實例::實例方法名`。
3. **特定類型的方法引用**：將特定對象的方法引用賦值給通用接口。例如：`類型::實例方法名`。
4. **構造器引用**：引用構造器，語法為`類名::new`。例如：`ArrayList::new`。

#### 構造器引用（Constructor Reference）：

構造器引用是方法引用的一個特例，用於創建物件。它類似於靜態方法引用，但語法為`類名::new`，用來創建與給定類構造函數兼容的物件。

方法引用和構造器引用的優點在於它們可以使代碼更加簡潔易讀，特別是對於一些簡單的操作，可以直接引用已有的方法或構造器，避免了重複編寫相似的Lambda表達式。

以下是一個使用方法引用和構造器引用的簡單示例：

#### 範例一

```java
import java.util.List;
import java.util.ArrayList;

public class MethodReferenceExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        
        // 使用方法引用打印每個名字
        names.forEach(System.out::println);
        
        // 使用構造器引用創建一個新的ArrayList物件
        List<String> newList = createList(ArrayList::new);
    }
    
    // 構造器引用示例
    public static <T> List<T> createList(Creator<List<T>> creator) {
        return creator.create();
    }
}

// 自定義的函數式接口，用於創建物件
interface Creator<T> {
    T create();
}
```

#### 範例二

```java
// 定義車輛工廠介面
interface ICarFactory {
    // 創建車輛物件
    CarBean getCar(String brand, int speed);

    // 靜態方法，打印車輛信息
    static void printCarInfo(CarBean car) {
        System.out.println("Car Name:" + car.getBrand() + " / Max Speed:" + car.getMaxSpeed());
    }
}

// 車輛類別
class CarBean {
    private String brand;
    private int maxSpeed;

    CarBean(String brand, int maxSpeed) {
        this.brand = brand;
        this.maxSpeed = maxSpeed;
    }

    String getBrand() {
        return brand;
    }

    int getMaxSpeed() {
        return maxSpeed;
    }
}

public class MethodAndConstructorReferenceTest {

    public static void main(String[] args) {

        // 測試通過Lambda創建車輛物件
        ICarFactory f = (String name, int maxSpeed) -> new CarBean(name, maxSpeed);
        ICarFactory f_3 = (o1, o2) -> new CarBean(o1, o2);

        // 測試方法引用創建車輛物件
        ICarFactory f_2 = CarBean::new;

        // 創建GTR車輛
        CarBean gtr = f.getCar("GTR", 320);

        // 創建BMW M3車輛
        CarBean m3 = f_2.getCar("BMW_M3", 300);
        
        // 創建Toyota corolla cross車輛        
        CarBean corollaCross = f_3.getCar("Toyota_corolla cross", 200);

        // 遍歷車輛列表，打印車輛信息
        List.of(gtr, m3, corollaCross ).forEach(ICarFactory::printCarInfo);

        // 輸出：
        // Car Name:GTR / Max Speed:320
        // Car Name:BMW_M3 / Max Speed:300
        // Car Name:Toyota_corolla cross / Max Speed:200
    }
}
```

總之，方法引用和構造器引用是Java 8引入的便利特性，使得代碼更加簡潔和可讀，尤其是在處理一些常見操作時。它們是函數式編程風格的重要組成部分，可以大大提高代碼的可維護性和可讀性。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xu-min-chang.gitbook.io/caster-develop-note/java/java-8/method-and-consturctor-reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
