views:

356

answers:

4

Should every Java class have a zero-argument constructor?

+21  A: 

No

If it makes no sense to create an instance of the class without supplying any information to the constructor then you need not have a zero-argument constructor.

A good example is java.awt.Color class, whose all ctors are argumented.

codaddict
Another good example - immutable types.
Andy Thomas-Cramer
@andy This deserves an answer of its own.
Trillian
A counter-example: Java Beans - http://en.wikipedia.org/wiki/Java_Beans#JavaBean_conventions
klez
+10  A: 

No, it doesn't make sense to always create zero argument constructors, the following scenarios are examples where it makes sense to provide at least a-some-argument-constructor

  1. Required dependencies that the class itself cannot create.
  2. There are no senseful defaults for the properties.

Cases where you want to have/need a zero-argument constructor:

  1. You want to comply to the JavaBeans specification (makes sense for simple data objects).
  2. All fields can be initialized using senseful defaults.
  3. You want to use a framework that needs it.

One of the mis-arguments for having a zero-argument constructor in my opinion is a long list of arguments. For that there are better solutions than accepting to initialize an object that isn't in a safe state after creation:

  1. Using the Builder pattern.
  2. Provide specialized container objects to configure an instance via the constructor.
  3. Provide multiple constructors where the base arguments of each one are the required parameters that cannot have defaults assigned.
Johannes Wachter
+3  A: 

No. However there are exceptions. For instance, if you intend your class to contain just static util methods or a singleton class or a class with just constants then you should create a private constructor with no arguments to prevent it from being explicitly instantiated.

CoolBeans
+4  A: 

As Andy Thomas-Cramer has already noted, it is even impossible:

class NeedsToBeImmutable {
    // For a class to be immutable, its reachable state
    // MUST be reached through a final field
    private final String stuff;

    //!!Compile error!!
    public NeedsToBeImmutable(){}

    public NeedsToBeImmutable(String stuff){
    this.stuff = stuff;
    }
    //getters...
}
Enno Shioji
Should we always have a zero-argument constructor? No. Is it always possible? Yes, but often undesirable. public NeedsToBeImmutable(){stuff="Hello World"} // no compile error but useless
emory