top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Java: Can we declare constructor as a private? If yes then what is use of private Constructor?

0 votes
627 views
Java: Can we declare constructor as a private? If yes then what is use of private Constructor?
posted Nov 25, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Yes we can declare constructor as private.If we declare then only one we can create. It is  known singleton class

1 Answer

0 votes

Yes, a constructor can be private. There are different uses of this. One such use is for the singleton design anti-pattern, which I would advise against you using. Another, more legitimate use, is in delegating constructors; you can have one constructor that takes lots of different options that is really an implementation detail, so you make it private, but then your remaining constructors delegate to it.

As an example of delegating constructors, the following class allows you to save a value and a type, but it only lets you do it for a subset of types, so making the general constructor private is needed to ensure that only the permitted types are used. The common private constructor helps code reuse.

public class MyClass {
 private final String value;
 private final String type;

 public MyClass(int x){
     this(Integer.toString(x), "int");
 }

 public MyClass(boolean x){
     this(Boolean.toString(x), "boolean");
 }

 public String toString(){
     return value;
 }

 public String getType(){
     return type;
 }

 private MyClass(String value, String type){
     this.value = value;
     this.type = type;
 }

}

answer Jan 19, 2017 by Dhaval Vaghela
...