Best way to handle multiple constructors in Java

Peter picture Peter · Feb 24, 2009 · Viewed 195.1k times · Source

I've been wondering what the best (i.e. cleanest/safest/most efficient) way of handling multiple constructors in Java is? Especially when in one or more constructors not all fields are specified:

public class Book
{

    private String title;
    private String isbn;

    public Book()
    {
      //nothing specified!
    }

    public Book(String title)
    {
      //only title!
    }

    ...     

}

What should I do when fields are not specified? I've so far been using default values in the class so that a field is never null, but is that a "good" way of doing things?

Answer

Craig P. Motlin picture Craig P. Motlin · Feb 24, 2009

A slightly simplified answer:

public class Book
{
    private final String title;

    public Book(String title)
    {
      this.title = title;
    }

    public Book()
    {
      this("Default Title");
    }

    ...
}