Reputation: 605
Should every Java class have a zero-argument constructor?
Upvotes: 19
Views: 5769
Reputation: 26882
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...
}
Upvotes: 4
Reputation: 20800
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.
Upvotes: 3
Reputation: 2735
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:
Upvotes: 10
Reputation: 455112
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.
Upvotes: 22