Here is the "Inheritance and finalize( )" example of ch7 in the book "thinking in java--2e":
Output by typing "java 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 Output by typing "java Frog finalize": 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 The book explains that-- "When you use composition to create a new class, you never worry about finalizing the member objects of that class. Each member is an independent object, and thus is garbage collected and finalized regardless of whether it happens to be a member of your class. With inheritance, however, you must override finalize( ) in the derived class if you have any special cleanup that must happen as part of garbage collection. When you override finalize( ) in an inherited class, it�s important to remember to call the base-class version of finalize( ), since otherwise the base-class finalization will not happen." Why "the base-class finalization will not happen" since Java API says "finalize()is called by the garbage collector on an object when garbage collection determines that there are no more references to the object"? (Sorry for the long post!)
The finalize() method of a given class is simply a method. All classes are derived from the Object class, which has a finalize method. This makes it possible for the JVM to 'always' call a finalize method on any object it is destroying. If you override finalize() in a class, then when an object of that class is destroyed, it's finalize method will be called, not it's superclass'. The action is much like any other method you've overridden, for instance, you wouldn't expect the equals() method of a class to include a call to it's parent class' equals() method, unless you explicitly designed your overridding method that way.
Joined: Aug 30, 2002
Thanks for your reply, Ray. I made a mistake to think that when the Frog object was created, it's parents were also created, actually were the contents of the constructors executed and there should be only 4 objects on the heap--1 Frog & 3 Characteristic.