up previous next contents
Next: The toString() Method Up: Classes and objects Previous: Initialization Blocks   Contents

Subsections

Garbage collection and finalize

  • Java performs garbage collection for you and eliminates the need to free objects explicitly.
  • This eliminates a common cause of errors in C/C++ and other languages (memory leaks). Never have to worry about dangling references.
  • When an object is no longer reachable the space it occupies can be reclaimed.
  • Space is reclaimed at the garbage collector's discretion.
  • Creating and collecting large numbers of objects can interfere with time-critical applications.

finalize

  • A class can implement a finalize method.
  • This method will be executed before an object's space is reclaimed.
  • Gives you a chance to use the state of the object to reclaim other non-Java resources.
  • finalize is declared like this:
        protected void finalize() throws Throwable {
           // ...
        }
    
  • Important when dealing with non-Java resources, such as open files.
  • Example: a class that opens a file should provide a close() method. Even then, there is no guarantee that the programmer will call the close() method, so it should be done in a finalize method.
        public void close()
        {
           if (file != null)
           {
              file.close();
              file = null;
           }
        }
        protected void finalize() throws Throwable
        {
           try
           {
              close();
           } 
           finally
           {
              super.finalize();
           }
        }
    
  • The close method is written carefully in case it is called more than once.
  • super.finalize is called to make sure your superclass is also finalized.
  • Train yourself to always do this.


up previous next contents
Next: The toString() Method Up: Classes and objects Previous: Initialization Blocks   Contents