標籤:package bsp 注意 sys xtend line system super ext
//: object/E05_DataOnly2.java/****************** Exercise 5 ****************** * Modify Exercise 4 so the values * of the data in DataOnly are assigned to and * printed in main(). ************************************************/package object;class Shape{ Shape(int i) { System.out.println("Shape 構造啦!"); } void dispose() { System.out.println("Shape dispose"); }}class Circle extends Shape{ Circle(int i) { super(i); System.out.println("Drawing Circle"); } @Override void dispose() { System.out.println("Erasing Circle"); super.dispose(); }}class Triangle extends Shape{ Triangle(int i) { super(i); System.out.println("Drawing Triangle"); } @Override void dispose() { System.out.println("Erasing Triangle"); super.dispose(); }}class Line extends Shape{ private int start, end; Line(int start, int end) { super(start); this.start = start; this.end = end; System.out.println("Drawing Line: " + start + ", " + end); } @Override void dispose() { System.out.println("Erasing Line: " + start + ", " + end); super.dispose(); }}public class E05_DataOnly2 extends Shape{ private Circle circle; private Triangle triangle; private Line[] lines = new Line[3]; public E05_DataOnly2(int i) { super(i + 1); //Shape 構造啦! // super(i + 1); for (int j = 0; j < lines.length; j++) //j=0:Shape 構造啦! Drawing Line: 0, 0;j=1:Shape 構造啦! Drawing Line: 1, 1 lines[j] = new Line(j, j * j); //j=2:Shape 構造啦! Drawing Line: 2, 4 circle = new Circle(1); //Shape 構造啦! Drawing Circle triangle = new Triangle(1); //Shape 構造啦! Drawing Triangle System.out.println("Combined 構造啦"); //Combined 構造啦 } @Override void dispose() { System.out.println("CDASystem dispose() "); //CDASystem dispose() circle.dispose(); //Erasing Triangle Shape dispose triangle.dispose(); //Erasing Circle Shape dispose for (int i = lines.length - 1; i >= 0; i--) //Erasing Line: 2, 4 Shape dispose lines[i].dispose(); //Erasing Line: 1, 1 Shape dispose //Erasing Line: 0, 0 Shape dispose super.dispose(); //Shape dispose } public static void main(String[] args) { E05_DataOnly2 x = new E05_DataOnly2(47); try { //... } finally { x.dispose(); } }}/*Output Shape 構造啦! Shape 構造啦! Drawing Line: 0, 0 Shape 構造啦! Drawing Line: 1, 1 Shape 構造啦! Drawing Line: 2, 4 Shape 構造啦! Drawing Circle Shape 構造啦! Drawing Triangle Combined 構造啦 CDASystem dispose() Erasing Triangle Shape dispose Erasing Circle Shape dispose Erasing Line: 2, 4 Shape dispose Erasing Line: 1, 1 Shape dispose Erasing Line: 0, 0 Shape dispose Shape dispose *///:~
以上注釋是程式輸出結果與程式執行過程的對照,需要注意的是:子類的建立與銷毀是伴隨著父類的建立與銷毀而進行的。
Java複用類中正確清理