JAVA程式員必讀:基礎篇(4)類和繼承

來源:互聯網
上載者:User
這節教程將開始討論對象的生命週期。包括怎樣建立對象、怎樣使用它以及在不使用它的時候將它從系統中清除。下面一個一個介紹:
4.1 對象的生命週期
  在這一小節中你可以學到怎樣建立和使用任何類型的對象,還討論了當對象不再需要的時候系統怎樣清除對象的。
  典型的JAVA程式建立對象,對象之間的互動是通過發送訊息來實現的。通過這些對象的互動,JAVA程式可以執行一個GUI、運行一個動畫或者通過網路發送和接收資訊。一旦對象已經完成了任務,它就被作為無用資訊被回收,它的資源可以由其它對象回收利用。
  以下是一個小的例子程CreateObjectDemo,它建立三個對象:一個是Point對象和兩個Rectange對象,你需要這三個來源程式才可以編譯這個程式:
public class CreateObjectDemo {
public static void main(String[] args) {
//建立一個Point對象和兩個Rectangle對象
Point origin_one = new Point(23, 94);
Rectangle rect_one = new Rectangle(origin_one, 100, 200);
Rectangle rect_two = new Rectangle(50, 100);
// 顯示rect_one的寬、高以及面積
System.out.println("Width of rect_one: " + rect_one.width);
System.out.println("Height of rect_one: " + rect_one.height);
System.out.println("Area of rect_one: " + rect_one.area());
// 設定rect_two的位置
rect_two.origin = origin_one;
// 顯示rect_two的位置
System.out.println("X Position of rect_two: " + rect_two.origin.x);
System.out.println("Y Position of rect_two: " + rect_two.origin.y);
// 移動rect_two並且顯示它的新位置
rect_two.move(40, 72);
System.out.println("X Position of rect_two: " + rect_two.origin.x);
System.out.println("Y Position of rect_two: " + rect_two.origin.y);
}
}
  一旦建立了對象,程式就可以操作對象並將它們有關的一些資訊顯示出來,以下是這個程式的輸出結果:
Width of rect_one: 100
Height of rect_one: 200
Area of rect_one: 20000
X Position of rect_two: 23
Y Position of rect_two: 94
X Position of rect_two: 40
Y Position of rect_two: 72
  這一節使用這個例子來在程式中描述對象的生命週期。從這你可以學到怎樣編寫代碼來建立、使用對象以及系統怎樣將它從記憶體中清除的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.