[Exercise 13 , Chapter4 in Thinking in Java 2/e]撰寫名為Tank 的class,此class 的狀態可以是滿的(filled)或空
的(emptied)。其死亡條件(death condition)是:object 被清
理時必須處於空狀態。請撰寫finalize() 以檢驗死亡條件是否成
立。請在main() ㆗測試Tank 可能發生的幾種使用方式。
                                  ---------这是侯捷/王建興 先生的合译Create a class called Tank that can be filled and emptied, and has a death condition that it must be empty when the object is cleaned up. Write a finalize( ) that verifies this death condition. In main( ), test the possible scenarios that can occur when your Tank is used. 
                                 ---------这是Bruce Eckel 先生的原文拜托! 拜托!!

解决方案 »

  1.   

    大家都没有做过吗??
    Disappointed.
      

  2.   

    public class Tank
    {
    private final int FULL=100;
    int contant;
    public void fill(int c) {
    if (c>0)
    {
    if (c+contant>FULL)
    {
    contant=FULL;
    }
    else 
    {
    contant+=c;
    }
    }
    System.out.println("current contant="+contant);
    }
    public void empty(int c) {
    if (c>0)
    {
    if (contant-c>0)
    {
    contant-=c;
    }
    else
    {
    contant=0;
    }
    }
    System.out.println("current contant="+contant);
    }
    protected void finalize()
                     throws Throwable {
    if (contant!=0)
    {
    System.out.println("not null!");
    System.out.println("emptyit force!");
    empty(FULL);
    }
    else {
    System.out.println("null!");
    }
    }
    public static void main(String[] args) 
    {
    Tank a=new Tank();
    Tank b=new Tank();
    a.fill(10);
    a.empty(10);
    a=null;
    b.fill(10);
    b=null;
    System.gc(); }
    }
      

  3.   

    果然不是很简单。
    虽然有一些语句看不懂(惭愧,小弟是初学者),但是很谢谢你! cherami(cherami)
    我把它copy了,慢慢研究!Thank you so much!! :-)  
    立刻把分数给你,虽然也许你并不是只为这些! 谢谢!