通過
//: Frog
// Testing finalize with inheritance
class DoBaseFinalization {
public static boolean flag = false;
}
class Characteristic {
String s;
Characteristic(String c) {
s = c;
System
}
protected void finalize() {
System
}
}
class LivingCreature {
Characteristic p =
new Characteristic(
LivingCreature() {
System
}
protected void finalize() {
System
// Call base
if(DoBaseFinalization
try {
super
} catch(Throwable t) {}
}
}
class Animal extends LivingCreature {
Characteristic p =
new Characteristic(
Animal() {
System
}
protected void finalize() {
System
if(DoBaseFinalization
try {
super
} catch(Throwable t) {}
}
}
class Amphibian extends Animal {
Characteristic p =
new Characteristic(
Amphibian() {
System
}
protected void finalize() {
System
if(DoBaseFinalization
try {
super
} catch(Throwable t) {}
}
}
public class Frog extends Amphibian {
Frog() {
System
}
protected void finalize() {
System
if(DoBaseFinalization
try {
super
} catch(Throwable t) {}
}
public static void main(String[] args) {
if(args
args[
DoBaseFinalization
else
System
new Frog(); // Instantly becomes garbage
System
// Must do this to guarantee that all
// finalizers will be called:
System
}
} ///:~
DoBasefinalization類只是簡單地容納了一個標志
分級結構中的每個類也包含了Characteristic類的一個成員對象
每個被覆蓋的finalize()至少要擁有對protected成員的訪問權力
在Frog
not finalizing bases
Creating Characteristic is alive
LivingCreature()
Creating Characteristic has heart
Animal()
Creating Characteristic can live in water
Amphibian()
Frog()
bye!
Frog finalize
finalizing Characteristic is alive
finalizing Characteristic has heart
finalizing Characteristic can live in water
從中可以看出確實沒有為基礎類Frog調用收尾模塊
Creating Characteristic is alive
LivingCreature()
Creating Characteristic has heart
Animal()
Creating Characteristic can live in water
Amphibian()
Frog()
bye!
Frog finalize
Amphibian finalize
Animal finalize
LivingCreature finalize
finalizing Characteristic is alive
finalizing Characteristic has heart
finalizing Characteristic can live in water
盡管成員對象按照與它們創建時相同的順序進行收尾
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27016.html