Java 技巧一:傳回 this

Java 程式

簡介

運算式

分枝

迴圈

陣列

函數

遞迴

錯誤處理

物件導向

封裝

繼承

多型

技巧

函式庫

字串

數學

正規表達式

容器

檔案

網路

資料庫

視窗

Thread

Listener

錯誤陷阱

相關檔案

相關資源

教學錄影

Eclipse

考題解答

訊息

相關網站

參考文獻

最新修改

簡體版

English

在物件導向的設計當中,我們可以用 Object.method() 這樣的語法執行某函數。假如一個函數沒有傳回值時,傳統上像 C 語言都會宣告為 void 而不傳回值,但是在物件導向語言中,我們通常會傳回其物件本身 (this),這樣讓我們可以直接透過 Object.method().method_1().method_2()…..method_k() 這樣的方式的串接性技巧執行函數,而不需要採用下列的冗長寫法。

Object.method_1();
Object.method_2();
...
Object.method_k();

程式範例一:傳回 this 並使用串接技巧的程式範例。

以下是一個採用上述技巧的範例,在程式中我們在 setName() 與 setAge() 函數中都傳回了 this 物件,於是我們在主程式中可以利用下列的單行語句直接建構出一個具有姓名與年齡的 Person 物件,而不需要分成數行撰寫。

Person p = new Person().setName("John").setAge(22);

檔案:Person.java

public class Person {
    public String name;
    public int age;
 
    public static void main(String[] args) {
        Person p = new Person().setName("John").setAge(22);
        System.out.println(p.ToString());
    }
 
    public Person setName(String name) {
        this.name = name;
        return this;
    }
 
    public Person setAge(int age) {
        this.age = age;
        return this;
    }
 
    public String ToString() {
        return "person:name="+name+" age="+age;
    }
}

執行結果

person:name=John age=22

程式範例一的改良:加上 print() 函數。

public class Person {
    public String name;
    public int age;
 
    public static void main(String[] args) {
        Person p = new Person().setName("John").setAge(22).print();
    }
 
    public Person setName(String name) {
        this.name = name;
        return this;
    }
 
    public Person setAge(int age) {
        this.age = age;
        return this;
    }
 
    public String ToString() {
        return "person:name="+name+" age="+age;
    }
 
    public Person print() {
        System.out.println(ToString());
        return this;
    }
}

教學錄影

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License