軌道
/
Java
Java
/
課程大綱
/
建構函式
建構

建構函式 在 Java

16 個練習

關於 建構函式

建立_類別_的實例,作法是透過new運算子呼叫它的建構子。 建構子是一種特殊的方法,目的是初始化剛建立好的實例。 建構子看起來和一般方法沒兩樣,但它沒有回傳型別,而且名稱要和類別名稱相同。

class Library {
    private int books;

    public Library() {
        this.books = 10;
    }
}

// This will call the constructor
var library = new Library();

和一般方法一樣,建構子也可以有參數。 建構子的參數通常會存成(私有的)欄位以便之後存取,或是用在一次性的計算裡。 就像把引數傳給一般方法一樣,引數也可以傳給建構子。

class Building {
    private int numberOfStories;
    private int totalHeight;

    public Building(int numberOfStories, double storyHeight) {
        this.numberOfStories = numberOfStories;
        this.totalHeight = numberOfStories * storyHeight;
    }
}

// Call a constructor with two arguments
var largeBuilding = new Building(55, 6.2)

你可以選擇要不要自己指定建構子。 如果沒有指定,編譯器會產生一個沒有參數的建構子:

class Elevator {
}

// This will call the (empty) generated constructor
var elevator = new Elevator();

如果欄位有指定初始值,編譯器產生的程式碼實際上會在建構子裡執行賦值。 因此,下面這兩個類別宣告在功能上是等價的:

class UsingFieldInitialization {
    private int players = 5;
}

class UsingConstructorInitialization {
    private int players;

    public UsingConstructorInitialization() {
        players = 5;
    }
}
透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 建構函式