【正文】
相同時 this 也可用來呼叫此物件的 methods this 也可以用來呼叫此物件的 constructor National Taiwan University Department of Computer Science and Information Engineering this 關(guān)鍵字 可以透過 this,呼叫相同類別底下的另一個建構(gòu)元 public class AClass { private int x, y。 private int width, height。 public AClass(){ this(0,0,0,0)。 } public AClass(int width, int height){ this(0,0,width,height)。 } public AClass(int x, int y, int width, int height){ = x。 = y。 = width。 = height。 } ... } National Taiwan University Department of Computer Science and Information Engineering this 關(guān)鍵字 具有二個建構(gòu)元的 Box 類別 class Box { double width, height, depth。 // 預(yù)設(shè)的建構(gòu)元 Box() { this(1, 2, 3)。 } // 可以自行指定長寬的建構(gòu)元 Box(int width, int height, int depth){ = width。 = height。 = depth。 } } National Taiwan University Department of Computer Science and Information Engineering this 關(guān)鍵字 Example: class BoxDemo { public static void main (String args []) { //宣告、配置與初始化 Box物件 Box myBox1 = new Box()。 Box myBox2 = new Box(10, 20, 30)。 double vol1, vol2。 //顯示第一個盒子的體積 ()。 //獲得第二個盒子的體積 ()。 } } National Taiwan University Department of Computer Science and Information Engineering Your Turn 建立一個 Rectangle 類別 此類別必須完成下列要求 建構(gòu)元 ? 初始化預(yù)設(shè)長、寬各為 4 ? 可自行設(shè)定矩形之長與寬 ? 可以複製相同物件的建構(gòu)元 (傳進去的參數(shù)為要 copy的物件 ) 顯示目前的長、寬之值 取得目前矩形之面積 畫矩形,由 * 構(gòu)成邊長 在 RectangleDemo 類別下,寫個 main() 來測試所有功能 National Taiwan University Department of Computer Science and Information Engineering Your Turn Hint class Rectangle { final int DEFAULT_LENGTH = 8。 final int DEFAULT_WIDTH = 4。 private int length。 private int width。 Rectangle(){ … } Rectangle(int length, int width){ … } Rectangle(Rectangle obj){ … } void showLW(){ … } double getArea(){ … } void drawRect(){ … } public static void main(String[] args){ … } } National Taiwan University Department of Computer Science and Information Engineering Your Turn 試著利用 Intellij IDEA 寫一個簡易使用者介面來測試你剛剛所寫的 Rectangle 類別的各項功能 1. 顯示長寬 2. 得到面積 3. 畫出矩形 4. 離開 Hint: 巢狀迴圈加判斷式 ******** * * * * ********