newbe question. Does it make any sense to have a private constructor in java with parameters? Since a private constructor can only be accessed within the class wouldn't any parameters have to be instance variables of that class?
Asked
Active
Viewed 2,605 times
3
-
2good use case would be for the [singleton pattern](https://stackoverflow.com/questions/2111768/singleton-class-in-java) – depperm Sep 26 '18 at 14:08
-
2It's also useful for the builder pattern. If the builder is a nested subclass of the main class it can access the private constructor and use it to create objects. – TiiJ7 Sep 26 '18 at 14:12
-
2You overlooked that a class can also have static methods that can access the private constructor. The actual values are therefore not restricted to instance variables. – Henry Sep 26 '18 at 14:15
2 Answers
2
Yes, if you are going to use that constructor in some method of your class itself and expose the method to other class like we do in the singleton pattern. One simple example of that would be like below :
public class MySingleTon {
private static MySingleTon myObj;
private String creator;
private MySingleTon(String creator){
this.creator = creator;
}
public static MySingleTon getInstance(String creator){
if(myObj == null){
myObj = new MySingleTon(creator);
}
return myObj;
}
public static void main(String a[]){
MySingleTon st = MySingleTon.getInstance("DCR");
}
}

Mark Rotteveel
- 100,966
- 191
- 140
- 197

Ankit Chauhan
- 646
- 6
- 20
-
what if instead of mySingleTon we had a MyUtility something like java's Math class. In that case does it still make sense? – DCR Sep 26 '18 at 17:15
-
Your actual example could be improved. You pass a parameter in `getInstance("DCR")` but if you reinvoke the method with a new parameter such as `getInstance("RCD")` it will not be reused. – davidxxx Sep 26 '18 at 19:33
1
Suppose that you have multiple public
constructors with the same variable to assign to a specific field or that you need to perform the same processing, you don't want to repeat that in each public constructor but you want to delegate this task to the common private
constructor.
So defining parameters to achieve that in the private
constructor makes sense.
For example :
public class Foo{
private int x;
private int y;
public Foo(int x, int y, StringBuilder name){
this(x, y);
// ... specific processing
}
public Foo(int x, int y, String name){
this(x, y);
// ... specific processing
}
private Foo(int x, int y){
this.x = x;
this.y = y;
}
}

davidxxx
- 125,838
- 23
- 214
- 215