【ThinkingInJava】4、關於finalize()的調用

來源:互聯網
上載者:User

標籤:java   java編程思想   finalize   

/*** 書本:《Thinking In Java》* 功能:關於finalize()的調用* 檔案:TerminationCondition.java* 時間:2014年10月6日17:49:09* 作者:cutter_point*/package Lesson5InitializationAndCleanUp;class Book{boolean checkedOut=false;//檢驗是否已經是知道的Book(boolean checkOut)//建構函式{checkedOut=checkOut;//初始化}//這裡定義一個方法void checkIn(){checkedOut=false;//尋找出來定義為假}//當程式結束被記憶體回收的時候,調用預設調用這個protected void finalize()//繼承自Object{if(checkedOut)//如果被檢測出來了{System.out.println("錯誤:檢測出來!");}else//沒有檢測出來{System.out.println("這個已經被簽入");}}}//主函數public class TerminationCondition {public static void main(String [] args){Book novel=new Book(true);//這是還沒有被回收的novel.checkIn();//改為falsenew Book(true);//匿名構造一個對象new Book(false);System.gc();//回收垃圾}}//從結果上看,只出來了            這個被回收了! 和      錯誤:檢測出來! //說明這個只有匿名對象建立的時候才會調用finalize



輸出結果:

這個已經被簽入
錯誤:檢測出來!







【ThinkingInJava】4、關於finalize()的調用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.