Should every Java class have a zero-argument 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.
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.
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.
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.
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.
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
Cases where you want to have/need a zero-argument constructor:
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With