靓仔China 2019-03-26 14:24 采纳率: 60%
浏览 310
已结题

关于finalize方法的问题,求解释代码

package initialization;

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 E12_TankWithTerminationCondition {
  public static void main(String args[]) {
    new Tank().empty();
    new Tank();
    // Don't empty the second one
    System.gc(); // Force finalization?
    System.runFinalization();
  }
} /* Output:
Tank 0 created
Tank 1 created
Error: tank 1 must be empty at cleanup
Tank 0 cleaned up OK
*///:~

  • 写回答

3条回答 默认 最新

  • 小小病魔 2019-03-26 16:37
    关注

    System.gc()是java中的垃圾回收机制,通过该方法调用提醒java虚拟机回收不用的对象,此时虚拟机会调用销毁对象的finalize()方法

    评论

报告相同问题?