Can a constructor be private? How is a private constructor useful?
-
10It should be noted that most answers given so far only consider the case of having _only_ private constructors. You can have public and private constructors in the same class, for purposes explained in Michael Aaron Safyan's answer. – Christian Semrau May 12 '10 at 06:06
-
@ChristianSemrau I'm looking at the jar for `lwjgl3` (beta) via Eclipse, and I found a private constructor in `org.lwjgl.Version`. Which brings me here. This class also has its own `main`, interestingly. Java is weird. – Braden Best Dec 28 '15 at 04:52
-
What happened when you tried it? Or looked it up? Was there a reason to distrust the compile or the JLS. – user207421 Jul 09 '17 at 12:08
16 Answers
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;
}
}
Edit
Looking at this answer from several years later, I would like to note that this answer is both incomplete and also a little bit extreme. Singletons are indeed an anti-pattern and should generally be avoided where possible; however, there are many uses of private constructors besides singletons, and my answer names only one.
To give a couple more cases where private constructors are used:
To create an uninstantiable class that is just a collection of related static functions (this is basically a singleton, but if it is stateless and the static functions operate strictly on the parameters rather than on class state, this is not as unreasonable an approach as my earlier self would seem to suggest, though using an interface that is dependency injected often makes it easier to maintain the API when the implementation requires larger numbers of dependencies or other forms of context).
When there are multiple different ways to create the object, a private constructor may make it easier to understand the different ways of constructing it (e.g., which is more readable to you
new ArrayList(5)
orArrayList.createWithCapacity(5)
,ArrayList.createWithContents(5)
,ArrayList.createWithInitialSize(5)
). In other words, a private constructor allows you to provide factory function's whose names are more understandable, and then making the constructor private ensures that people use only the more self-evident names. This is also commonly used with the builder pattern. For example:MyClass myVar = MyClass .newBuilder() .setOption1(option1) .setOption2(option2) .build();

- 93,612
- 16
- 138
- 200
-
7from a testability point of view - they represent a global state, which is hard to predict (and test) – Bozho May 12 '10 at 05:38
-
@Vuntic, please see: http://sites.google.com/site/michaelsafyan/coding/design/coding-best-practices/avoid-global-variables-environment-variables-and-singletons – Michael Aaron Safyan May 12 '10 at 05:41
-
13@Vuntic, the short answer is that singletons result in shared mutable state and, more importantly, baking the singleton-ness into the API makes it inflexible, makes it hard to test, and makes things like hell when it turns out that the singleton assumption is not correct. While it is fine to have singletons in the sense that you only instantiate the object once, enforcing singleton-ness via private constructor and static instantiation function leads to an incredibly messy and fragile design. A better approach is to pass around the interface that the singleton conforms to... – Michael Aaron Safyan May 12 '10 at 05:43
-
7... and to construct only one instance of it, and then pass it around. This approach is known as dependency injection, and leads to cleaner, more flexible designs. – Michael Aaron Safyan May 12 '10 at 05:43
-
24The real anti-pattern here is overusage imho. This applies to any pattern that is used out of habit without giving thought to what is best in the given situation. – rsp May 12 '10 at 13:43
-
1I've just lately been diving into openGL... if you think singletons are evil, good GOD you'll hate that... currently about 80% of my mini-program to test that stuff is in either singletons or static methods. This is not a bad thing. – amara May 12 '10 at 14:07
-
5So...former chief Java architect at Google Joshua Bloch advocates static factory methods that use private constructors (Effective Java 2nd edition)...considering his expertise with the language and his creation of the Java Collections Framework, I would say private constructors alongside static factory methods are a very viable and recommended use of private constructors – Zack Macomber Jan 23 '13 at 14:56
-
@ZackMacomber, that's an excellent point. Will update my answer. – Michael Aaron Safyan May 13 '14 at 04:31
-
In `Singleton` you should clear reference yourself but ain't **anti-patterns**! – Muhammad Babar Aug 21 '14 at 13:20
-
Yes, it is an anti pattern. If you think you need a Singleton, you really need a parameter that you optionally inject using a dependency injection framework. – Michael Aaron Safyan Aug 21 '14 at 16:53
-
@MichaelAaronSafyan then whats the solution if want a class to have only one instance? – Muhammad Babar Sep 26 '14 at 06:01
-
2@MuhammadBabar, I believe I answered that, but to reiterate... you guarantee that there is only one instance externally to the class. That is, you construct only one instance and then pass that one instance to all places that use it (as opposed to calling a static getInstance function on the class everywhere it is used). This can be done manually or with a dependency injection framework. – Michael Aaron Safyan Sep 29 '14 at 08:30
-
@MichaelAaronSafyan thanks for the reiterate. `This can be done manually or with a dependency injection framework.` I would be grateful if you can show any example code? – Muhammad Babar Sep 29 '14 at 10:21
-
`That is, you construct only one instance and then pass that one instance to all places that use it` from this i understand that `the programmer have to take care of creating only one instance and then passing reference to other classes` Am i right! – Muhammad Babar Sep 29 '14 at 10:27
-
The documentation for Dagger or Guice would be a good place to look for examples of how to do it with a dependency injection framework (they also show how to do it manually to compare the approaches). – Michael Aaron Safyan Sep 29 '14 at 16:22
-
In the second usage, what is the difference between the constructor that is private and a private method? – Sreekanth Karumanaghat Jan 31 '17 at 08:58
-
@SreekanthKarumanaghat they are pretty similar. The main thing here, though, is that by making all constructors private, it forces the object to be constructed indirectly, through a visible static function on the class (which, in turn, calls the private constructor). The visible static function can then provide a clearer API. – Michael Aaron Safyan Jan 31 '17 at 13:36
I expected that someone would've mentioned this (the 2nd point), but.. there are three uses of private constructors:
to prevent instantiation outside of the object, in the following cases:
- singleton
- factory method
- static-methods-only (utility) class
- constants-only class
.
to prevent sublcassing (extending). If you make only a private constructor, no class can extend your class, because it can't call the
super()
constructor. This is some kind of a synonym forfinal
overloaded constructors - as a result of overloading methods and constructors, some may be private and some public. Especially in case when there is a non-public class that you use in your constructors, you may create a public constructor that creates an instance of that class and then passes it to a private constructor.

- 588,226
- 146
- 1,060
- 1,140
-
10in Java, the keyword "final" is used to prevent subclassing; it is not necessary to make the constructor private for that. – Michael Aaron Safyan May 12 '10 at 05:45
-
13it is not necessary, but you can. I mentioned the `final` keyword as a way to achieve this. – Bozho May 12 '10 at 05:54
-
1The 'following cases' are necessarily incomplete but in any case irrelevant. It prevents instantiation from outside the *class,* in *all* cases, not just the ones enumerated here. – user207421 Jul 09 '17 at 12:08
-
@MichaelAaronSafyan, this is not entirely true. An abstract class may not be final (Java 8). Why would I want to make a class abstract and final... if it provides all the implementations (subclasses) by means of static methods, and I want it to be final in that sense – Werner Erasmus Aug 25 '18 at 13:46
Yes.
This is so that you can control how the class is instantiated. If you make the constructor private, and then create a visible constructor method that returns instances of the class, you can do things like limit the number of creations (typically, guarantee there is exactly one instance) or recycle instances or other construction-related tasks.
Doing new x()
never returns null
, but using the factory pattern, you can return null
, or even return different subtypes.
You might use it also for a class which has no instance members or properties, just static ones - as in a utility function class.

- 23,931
- 5
- 55
- 71
-
but you could keep track of the number of instances simply by using a static variable; it isn't necessary to make the constructor private for that. – Michael Aaron Safyan May 12 '10 at 04:30
-
1@michael indeed you can, but it is not as elegant, and the restriction is not as obvious to the users of the class. – Jon May 12 '10 at 05:13
-
1@Jon, sorry, I misunderstood... I thought you were merely counting the number of instances, not restricting the number of instances. – Michael Aaron Safyan May 12 '10 at 05:44
Yes. Class can have private constructor. Even abstract class can have private constructor.
By making constructor private, we prevent the class from being instantiated as well as subclassing of that class.
Here are some of the uses of private constructor :

- 550
- 5
- 15
Private Constructors can be defnied in the Java for the following reasons
To have control on the instantiation of the Java objects, it wont allow you to create an instance of an object.
It wont allow the class to be Subclassed
This has a special advantage when implementing the singleton Pattern, Private contstructors are used for it and have a control on the creating the instance for the whole application.
when you want to have a class with all constants defined and Does not require its instance any more, then we declare that class as a private constructor.

- 15,598
- 27
- 89
- 112
-
They can be declared for any reason whatsoever, or no reason at all, just the implementor's whim. – user207421 Jul 09 '17 at 12:10
-
Private constructor do not prevent subclassing (https://self-learning-java-tutorial.blogspot.com/2018/05/can-private-constructor-prevent-sub.html) – Hari Krishna Jan 09 '20 at 05:28
Yes.
A private constructor is used to prevent instance initializing, such as the Math final class you use in java. Singleton also use private constructor

- 729
- 3
- 14
- 23
Yes, class can have a private constructor. It is needed as to disallow to access the constructor from other classes and remain it accessible within defined class.
Why would you want objects of your class to only be created internally? This could be done for any reason, but one possible reason is that you want to implement a singleton. A singleton is a design pattern that allows only one instance of your class to be created, and this can be accomplished by using a private constructor.

- 709
- 5
- 8
yes a constructor can be private. A private Constructor prevents any other class from instantiating example of private constructor
public class CustomHttpClient {
private static HttpClient customHttpClient;
/** A private Constructor prevents any other class from instantiating. */
private CustomHttpClient() {
}}

- 1,113
- 7
- 7
Can a constructor be private? How is a private constructor useful?
Yes it can. I consider this another example of it being useful:
//... ErrorType.java
public enum ErrorType {
X,
Y,
Z
}
//... ErrorTypeException.java
import java.util.*;
import java.lang.*;
import java.io.*;
//Translates ErrorTypes only
abstract public class ErrorTypeException extends Exception {
private ErrorTypeException(){}
//I don't want to expose thse
static private class Xx extends ErrorTypeException {}
static private class Yx extends ErrorTypeException {}
static private class Zx extends ErrorTypeException {}
// Want translation without exposing underlying type
public static Exception from(ErrorType errorType) {
switch (errorType) {
case X:
return new Xx();
case Y:
return new Yx();
default:
return new Zx();
}
}
// Want to get hold of class without exposing underlying type
public static Class<? extends ErrorTypeException> toExceptionClass(ErrorType errorType) {
switch (errorType) {
case X:
return Xx.class;
case Y:
return Yx.class;
default:
return Zx.class;
}
}
}
In the case here above, it prevents the abstract class from being instantiated by any derived class other than it's static inner classes. Abstract classes cannot be final, but in this case the private constructor makes it effectively final to all classes that aren't inner classes

- 3,988
- 17
- 31
Private constructors prevent a class from being explicitly instantiated by callers see further information on PrivateConstructor

- 3,026
- 3
- 41
- 50
Yes and it is used to prevent instantiation and subsequently overriding. This is most often used in singleton classes.

- 5,735
- 10
- 41
- 66
Inspired by Robert C. Martin's "Clean Code", example I fiddled together:
/**
When overloading constructors, it is best practise to only allow the use of
different constructors than the standart one by explicitly enforcing the
useage of a static function to highlight the use of the overloaded constructor
in example:
Animal a = Animal.CreateInsectOrArachnia(2, "black", 8); //hatch a black widow
*/
class Animal
{
private int size;
private String color;
private int legs;
public Animal(int size, String color)
{
this.size = size;
this.color = color;
this.legs = 4;
}
//will prevent the instanciation of Animal with this constructor
private Animal(int size, String color, int legs)
{
this.size = size;
this.color = color;
this.legs = legs;
}
public static Animal CreateInsectOrArachnia(int size, String color, int legs)
{
return new Animal (size, color, legs);
}
}
Martins explicitly states that users should be prevented from accessing constructors other than the "standart constructor" and should be forced to use static initialisation functions to underline that "what you do may not be wrong but it differs from expected useage of this class"
[he did not use this exact wording, i tried to squeeze it into this definition - sorry Robert :^) ]
As a side note, it is totally okay to completely declare the only constructor in a class (aka standart-constructor) as private and have a static function return a class instance - see singleton pattern. it is highly discouraged to implement a singleton pattern tho, except maybe for some use-cases where communication only flows in one direction, f.e. when writing a logger class

- 576
- 5
- 26
According to me we can declare constructor as a private and also we
can get the instance of that class in the subclass by using static method in class in which we declare constructor and then return class object. we class this method from to the sub class
by using classname.method
name bcz it is static method and the we will get the instance of class in which we declare const.

- 10,519
- 8
- 40
- 45
Basic idea behind having a private constructor is to restrict the instantiation of a class from outside by JVM, but if a class having a argument constructor, then it infers that one is intentionally instantiating.

- 5,319
- 6
- 35
- 43