Topic: 一个关于finalize的问题 请高手赐教!!

  Print this page

1.一个关于finalize的问题 请高手赐教!! Copy to clipboard
Posted by: luxifa0425
Posted on: 2007-11-19 17:28

class DoBaseFinalization {
public static boolean flag=false;
}

class Base {
Base() {
System.out.println("Base()");
}
protected void finalize() throws Throwable {
System.out.println("Base finalized()!");
if(DoBaseFinalization.flag)
super.finalize();
}
}

class Second extends Base {
Second() {
System.out.println("Second()");
}
protected void finalize() throws Throwable {
System.out.println("Second finalized()!");
if(DoBaseFinalization.flag)
super.finalize();
}
}

class Third extends Second {
Third() {
System.out.println("Third()");
}
protected void finalize() throws Throwable {
System.out.println("Third finalized()!");
if(DoBaseFinalization.flag)
super.finalize();
}
}

public class C07_11 {
public static void main(String[] args) {
if((args.length!=0)&&(args[0].equals("finalize")))
DoBaseFinalization.flag=true;
else
System.out.println("Not Finalized!");
//new Third();
System.out.println("Bye!");
System.gc();
}
}

这是一个子类都能正确呼叫base class的finalize的例子,上面这段标记的地方如果用Third td=new Third(),那么就算引数输入finalize,也不能呼叫finalize的方法,一定要使用new Third(),我不知道为什么?请各位高手赐教阿!!!

2.Re:一个关于finalize的问题 请高手赐教!! [Re: luxifa0425] Copy to clipboard
Posted by: weiyidexuan
Posted on: 2007-11-20 01:59

you can use the method System.runFinalizersOnExit(true);
but this method is outdated.

3.Re:一个关于finalize的问题 请高手赐教!! [Re: luxifa0425] Copy to clipboard
Posted by: tianqinhot
Posted on: 2007-11-20 17:22

Third td=new Third()于new Third()的区别在于:前者创建Third对象并且被td引用;jvm不会把他当成垃圾;因此System.gc(); 时不会启动Garbage;后者只是单纯的创建一个对象没有被引用.jvm则会把该对象当做垃圾;System.gc();时这回调用finalize();
这只是个人的理解哦.希望有所帮助;

4.Re:一个关于finalize的问题 请高手赐教!! [Re: luxifa0425] Copy to clipboard
Posted by: luxifa0425
Posted on: 2007-11-20 18:24

似乎明白了 谢谢啊~~


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923