//: initialization/TerminationCondition.java
// Using finalize() to detect an object that
// hasn't been properly cleaned up.
class Book {
boolean checkedOut = false;
Book(boolean checkOut) {
checkedOut = checkOut;
}
void checkIn() {
checkedOut = false;
}
protected void finalize() {
if(checkedOut)
System.out.println("Error: checked out");
// Normally, you'll also do this:
// super.finalize(); // Call the base-class version
}
}
public class TerminationCondition {
public static void main(String[] args) {
Book novel = new Book(true);
// Proper cleanup:
novel.checkIn();
// Drop the reference, forget to clean up:
new Book(true);
// Force garbage collection & finalization:
System.gc();
}
} /* Output:
Error: checked out
*///:~
问题1:输出为什么是“Error: checked out”,在哪里调用了finalize()方法,(因为只有finalize()方法里有打印输出语句System.out.println("Error: checked out");)
问题2:书上说,在main()方法里,由于错误,有一本书(即Book对象)为被check in, 要是没有finalize()来验证终结条件,见很难发现这种缺陷,真是怎么回事
问题3:main()方法是不是调用了两次构造方法,第一次“Book novel = new Book(true);”,第二次new Book(true);
问题2:应该是“将很难发现这种缺陷,这是怎么回事”
繁星淼淼
慕斯709654
忽然笑
守着星空守着你
随时随地看视频慕课网APP
相关分类