Possible Duplicate:
What is the use of making constructor private in a class?
When is it useful to use a private constructor? What about a protected one?
Possible Duplicate:
What is the use of making constructor private in a class?
When is it useful to use a private constructor? What about a protected one?
it's useful when you want to prevent external instantiation of an object, e.g. static factory classes, singletons, and etc.
I can think of a few uses for private
:
A totally contrived example of the last:
private MyClass(int a) {
this.a = a}
public MyClass(int a, String B) {
this(a);
this.b = b;
}
public MyClass(int a, double c) {
this(a);
this.b = Double.toString(c);
}
Similar reasoning for protected
, it just extends the privileged few to subclasses and package neighbors.
Singleton pattern uses a private constructor to control the instantiation of an object. Another use case that you may encounter is when you would like to have a special constructor used in unit tests (if you run unit tests without dependency injection frameworks), so you will not make it public, but package protected and declare the unit test in the same package.