O'Reilly logo

Effective Java™: Programming Language Guide by Joshua Bloch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2. Creating and Destroying Objects

This chapter concerns creating and destroying objects: when and how to create objects, when and how to avoid creating them, how to ensure that objects are destroyed in a timely manner, and how to manage any cleanup actions that must precede object destruction.

Item 1: Consider providing static factory methods instead of constructors

The normal way for a class to allow a client to obtain an instance is to provide a public constructor. There is another, less widely known technique that should also be a part of every programmer's toolkit. A class can provide a public static factory method, which is simply a static method that returns an instance of the class. Here's a simple example from the class Boolean ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required