How to avoid traps and correctly override methods from java.lang.Object

Avoid incorrect implementations and bugs by following these guidelines

Page 3 of 3
    protected void finalize() throws Throwable
    {
        super.finalize();
    }

Second, you should not depend on the finalize method being called. There is no guarantee of when (or if) objects will get garbage collected and thus no guarantee that the finalize method will be called before the running program exits. Finally, remember that code in finalize might fail and throw exceptions. You may want to catch these so the finalize method can continue.

protected void finalize() throws Throwable { try { // Do stuff here to clean up your object. } catch (Throwable t) { }

super.finalize(); }

In general, finalize doesn't need to be overridden.

Conclusion

There are traps to overriding all of the nonfinal methods inherited from java.lang.Object. Some of them are subtle enough that even classes provided in the core Java libraries get them wrong. Nevertheless, with a bit of care, you can implement the methods correctly.

When building large products and when constructing third-party class libraries, it is important to take the care needed to get these implementations right. After all, some developer might read the documentation and assume your code does what the documentation says. Failing to implement these methods correctly for large projects can result in extra time spent debugging. When implementing these methods in libraries sold commercially, it is even more important to implement these methods correctly; you cannot easily fix things once the library has been released. Failing to implement these methods properly can result in your library being harder to use and extend than it should be. Finally, for smaller projects, it can sometimes be reasonable to meet most, but not all, of the requirements for these methods. In those cases you should at least make your decision consciously and document it.

Mark Roulo has been programming professionally since 1989 and has been using Java since the alpha-3 release. He has been programming almost exclusively in Java for the past few years. His interests include portable, multithreaded, and distributed programming.

Learn more about this topic

  • Both the javadoc and the source code for the methods in java.lang.Object can be found at Sun's Java Web site http://java.sun.com
  • The Eiffel programming language takes the notion of design-by-contract very seriously. This paper provides a good discussion of this notion http://www.eiffel.com/doc/manuals/technology/contract/index.html
| 1 2 3 Page 3