看板java
标 题继承和finalize()的问题
发信站无名小站 (Sat Feb 25 19:54:11 2006)
转信站ptt!ctu-reader!Spring!news.nctu!news.ntu!news.ee.ttu!netnews.csie.nctu
以下是Thinking in Java中译本当中P333~335的code
class DoBaseFinalization{
public static boolean flag=false;
}
class Characteristic{
String s;
Characteristic(String c){
s=c;
System.out.println("Creating Characteristic "+s);
}
protected void finalize(){
System.out.println("finalizing Characteristic "+s);
}
}
class LivingCreature{
Characteristic p =new Characteristic("is alive");
LivingCreature(){
System.out.println("LivingCreature()");
}
protected void finalize() throws Throwable{
System.out.println("LivingCreature finalize");
if(DoBaseFinalization.flag)
super.finalize();
}
}
class Animal extends LivingCreature{
Characteristic p =new Characteristic("hac heart");
Animal(){
System.out.println("Anaimal()");
}
protected void finalize() throws Throwable{
System.out.println("Animal finalize");
if(DoBaseFinalization.flag)
super.finalize();
}
}
class Amphibian extends Animal{
Characteristic p =new Characteristic("can live in water");
Amphibian(){
System.out.println("Amphibian()");
}
protected void finalize() throws Throwable{
System.out.println("Amphibian finalize");
if (DoBaseFinalization.flag)
super.finalize();
}
}
public class Frog extends Amphibian {
Frog(){
System.out.println("Frog()");
}
protected void finalize() throws Throwable{
System.out.println("Frog finalize");
if(DoBaseFinalization.flag)
super.finalize();
}
public static void main(String[] args) {
if(args.length !=0 && args[0].equals("finalize"))
DoBaseFinalization.flag=true;
else
System.out.println("Not finalizing bases");
new Frog();
System.out.println("Bye!!");
System.gc();
}
}
然後执行所得的结果如下:
Not finalizing bases
Creating Characteristic is alive
LivingCreature()
Creating Characteristic has heart
Animal()
Creating Characteristic can live in water
Amphibian()
Frog()
Bye!
finalizing Characteristic can live in water
finalizing Characteristic has heart
finalizing Characterisitc is alive
Frog finalize
在此提出几个问题,多谢指导!!
1.System.gc之後的动作会呼叫finalize(),但带有extends的关系中,顺序是什麽呢?
2.在该本书中的执行结果为,请问是不是有误呢?
(上面略)
Bye!
Frog finalize
finalizing Characterisitc is alive
finalizing Characteristic has heart
finalizing Characteristic can live in water
--
夫兵者不祥之器物或恶之故有道者不处君子居则贵左用兵则贵右兵者不祥之器非君子
之器不得已而用之恬淡为上胜而不美而美之者是乐杀人夫乐杀人者则不可得志於天下
矣吉事尚左凶事尚右偏将军居左上将军居右言以丧礼处之杀人之众以哀悲泣之战胜以
丧礼处之道常无名朴虽小天下莫能臣侯王若能守之万物将自宾天地相合以降甘露民莫
之令而自均始制有名名亦既有夫亦将知止知止可以不 h99-158.dorm1.ccit.edu.tw海