Java private constructor with parameters

2.8k Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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");
    } 
}
0
On

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;
   } 
}