题目:
编写具有finalize() 方法的类,并在方法中打印消息。在main() 中为该类创建一个对象。让finalize() 总会被调用。
解答:
import java.util.*;
public class chapterFive {
protected void finalize(){
System.out.println("finalize() called");
}
public static void main(String[] args){
new chapterFive();
System.gc();
System.runFinalization();
}
}
结果如下:
Calling System.gc() and System.runFinalization() in sequence will probably but not necessarily call your finalizer (The behavior of finalize has been uncertain from one version of JDK to another.) The call to these methods is just a request; it doesn’t ensure the finalizer will actually run. Ultimately, nothing guarantees that finalize() will be called.
如果觉得不错,就用点赞或者关注来代替五星好评!
谢谢~