First page Back Continue Last page Summary Text


In C++ objects die (the code in the "destructor" executes), and an object that owns a resource can be relied upon to release that resource when it dies. This is convenient for the client code, because it need take no action beyond destroying any objects it creates.
Programmers coming to Java from C++ often make the mistake of translating the C++ idea ‘destructor’ into Java ‘finalize’, and some of the early Java material even encouraged this misconception.
It doesn’t work: C++ ‘destructors’ have the responsibility of decomposing the object, including releasing resources owned by it – but unlike finalize a destructor is guaranteed to execute at a particular point in the program execution.
In Java the only way to guarantee that a method on an object is executed at a particular time is to call it before the object is forgotten.
In this code fragment it should be obvious that the resources will be released whether or not paint() propagates an exception. We’ll be coming back to this Allocate-Use-Release coding motif later - for the moment just look at the three significant steps: allocate, use, release and the logic that binds them together.