Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we always have a zero-argument constructor in a Class?

Should every Java class have a zero-argument constructor?

like image 863
user421814 Avatar asked Aug 16 '10 14:08

user421814


People also ask

Should a class always contain a no arg constructor?

No. The first thing a subclass constructor must do is to invoke one of the superclass constructors. If you don't, then the compiler calls the no-arg constructor of the superclass for you. But of course that fails if the superclass doesn't have one.

Does every class have a no-argument constructor?

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor.

Why do we need a no arg constructor?

newInstance() method, which requires a no-argument constructor to create an instance. It's effectively equivalent to the new Entity(). This method throws InstantiationException if it doesn't found any no-argument constructor in the Entity class, and that's why it's advised to provide a no-argument constructor.

What happens if your class doesn't have a no-argument constructor?

In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object , which does have a no-argument constructor. You can use a superclass constructor yourself.


2 Answers

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.

like image 182
codaddict Avatar answered Sep 20 '22 17:09

codaddict


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.
like image 43
Johannes Wachter Avatar answered Sep 23 '22 17:09

Johannes Wachter