May 19
每個建構式的第一行必須是 this call*或 super call*,若沒有指定 constructor call,編譯器會自動幫你建構一個沒有參數的 superclass constructor。
*this() 呼叫同一 class的其他 constructor
*super() 呼叫 superclass constructor
每個 constructor 可以選擇呼叫 super() 或 this(),但不能同時叫用。
使用 this() 來從某個 constructor 呼叫同一 class 的另一個 constructor。
this() 只能用在 constructor 中,且必須是第一述句。
super() 與 this() 不可兼得也。
—Head First Java
一般來說,在沒有參數的 constructor 中直接使用 this() 來呼叫另一個有參數的建構方法,可以少寫一些重複的程式碼。
Constructor Chain Exercise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | // File : ConstructorChain.java // Purpose: Illustrate constructor chaining. // Author : Fred Swartz // Date : 5 May 2003 class ConstructorChain { public static void main(String[] args) { Child c = new Child(); } } class Child extends Parent { Child() { System.out.println("Child() constructor"); } } class Parent extends Grandparent { Parent() { this(25); //呼叫目前具有相同型態參數的建構子 System.out.println("Parent() constructor_CodeFirstLine"); //CodeFirstLine用來標示順序以釐清運作原理 } Parent(int x) { System.out.println("Parent(" + x + ") constructor_CodeSecondLine"); //CodeSecondLine用來標示順序以釐清運作原理 } } class Grandparent { Grandparent() { System.out.println("Grandparent() constructor"); } } |
執行結果:
Grandparent() constructor
Parent(25) constructor_SecondLine
Parent() constructor_FirstLine
Child() constructor
Ref1: Java: Constructor Chaining Exercise 1
Ref2: Java this、super的用法 – 三驾马车 – BlogJava
Ref3: 建構方法(Constructor)
溫故知新
載入中…
歷史上的今天..
- Yahoo! Kimo 和 CTV 不知道在想啥? - 2007







最新回應