Content received from:

Q:When should I use constructors, and when should I use other methods?
Wednesday, December 28, 2005 (00:00:00)

Posted by jalex

Q:When should I use constructors, and when should I use other methods?

Answer: The glib answer is to use constructors when you want a new object; that's what the keyword new is for. The infrequent answer is that constructors are often over-used, both in when they are called and in how much they have to do. Here are some points to consider
  • Modifiers: As we saw in the previous question, one can go overboard in providing too many constructors. It is usually better to minimize the number of constructors, and then provide modifier methods, that do the rest of the initialization. If the modifiers return this, then you can create a useful object in one expression; if not, you will need to use a series of statements. Modifiers are good because often the changes you want to make during construction are also changes you will want to make later, so why duplicate code between constructors and methods.
  • Factories: Often you want to create something that is an instance of some class or interface, but you either don't care exactly which subclass to create, or you want to defer that decision to runtime. For example, if you are writing a calculator applet, you might wish that you could call new Number(string), and have this return a Double if string is in floating point format, or a Long if string is in integer format. But you can't do that for two reasons: Number is an abstract class, so you can't invoke its constructor directly, and any call to a constructor must return a new instance of that class directly, not of a subclass. A method which returns objects like a constructor but that has more freedom in how the object is made (and what type it is) is called a factory. Java has no built-in support or conventions for factories, but you will want to invent conventions for using them in your code.
  • Caching and Recycling: A constructor must create a new object. But creating a new object is a fairly expensive operation. Just as in the real world, you can avoid costly garbage collection by recycling. For example, new Boolean(x) creates a new Boolean, but you should almost always use instead (x ? Boolean.TRUE : Boolean.FALSE), which recycles an existing value rather than wastefully creating a new one. Java would have been better off if it advertised a method that did just this, rather than advertising the constructor. Boolean is just one example; you should also consider recycling of other immutable classes, including Character, Integer, and perhaps many of your own classes. Below is an example of a recycling factory for Numbers. If I had my choice, I would call this Number.make, but of course I can't add methods to the Number class, so it will have to go somewhere else.

      public Number numberFactory(String str) throws NumberFormatException {
        try {
          long l = Long.parseLong(str);
          if (l >= 0 && l < cachedLongs.length) {
            int i = (int)l;
            if (cachedLongs[i] != null) return cachedLongs[i];
            else return cachedLongs[i] = new Long(str);
          } else {
            return new Long(l);
        } catch (NumberFormatException e) {
          double d = Double.parseDouble(str);
          return d == 0.0 ? ZERO : d == 1.0 ? ONE : new Double(d);
      private Long[] cachedLongs = new Long[100];
      private Double ZERO = new Double(0.0);
      private Double ONE = new Double(1.0);
We see that new is a useful convention, but that factories and recycling are also useful. Java chose to support only new because it is the simplest possibility, and the Java philosophy is to keep the language itself as simple as possible. But that doesn't mean your class libraries need to stick to the lowest denominator. (And it shouldn't have meant that the built-in libraries stuck to it, but alas, they did.)

This tip is reprinted on by by courtesy of Peter Norvig I am thankful for his important contributions to my site - 21 Infrequently Answered Java Questions. Alexandre Patchine