Java 习题 (42)

题目:
编写名为Tank的类,此类的状态可以是“满的” 或 “空的”。 其终结条件是:对象被清理时必须处于空状态。请编写finalize() 以检验终结条件是否成立。在main() 中测试 Tank 可能发生的几种使用方式。

解答:

import java.util.*;

class Tank{
    static int counter;
    int id = counter++;
    boolean full;
    public Tank(){
        System.out.println("Tank " + id + " created");
        full = true;
    }

    public void empty() {
        full = false;
    }

    protected void finalize() {
        if(full){
            System.out.println("Error: tank " + id + " must be empty at cleanup");
        } else {
            System.out.println("Tank " + id + " cleaned up OK");
        }
    }

    public String toString() {
        return "Tank " + id;
    }
}

public class chapterFive {
    public static void main(String[] args){
        new Tank().empty();
        new Tank();
        System.gc();
        System.runFinalization();
    }
}

结果如下:
在这里插入图片描述
如果觉得不错,就用点赞或者关注来代替五星好评~
谢谢~

猜你喜欢

转载自blog.csdn.net/BSCHN123/article/details/107446023
42