Can a constructor in Java be private or final?

73
down vote

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;
}
}
http://stackoverflow.com/questions/2816123/can-a-constructor-in-java-be-private

Leave a Reply