What is the use of private constructor in java?
In Java, we can use any access modifier (i.e. public, protected or private) with constructor. So, what are the uses of making constructor private? First thing that strikes your mind is Singleton Design Pattern which is also one of the most asked Core Java Interview Question to the 3-4 yr exp Java developers.
Apart from creating singleton class, private constructor also has many other pivotal uses. With private constructor instance of that class can only be created
Here are some of the uses of
- Singleton Design Pattern
- To limit the number of instance creation
-
To give
meaningful name for object creation usingstatic factory method - Static Utility Class or Constant Class
- To Prevent Subclassing
- Builder Design Pattern
1) Singleton Design Pattern
In Singleton design pattern, we
To make a class singleton in Java, below things need to be taken care:
-
Define all constructors to
be protected
or private
. -
Define
one private static
attribute in the "single instance" class. -
Define
a public static
accessor function in the class. - Clients can only use the accessor function to manipulate the Singleton.
Here is the sample code :
public class SingletonClass{ //Private static instance is created at the time of class loading private static SingletonClass instance = new SingletonClass(); // Constructor made private so that no new instance can be created private SingletonClass(){ } // Static method to return the instance to the client public static SingletonClass getInstance(){ return instance; } }
For more details on this, read our article Singleton Design Pattern
2) To Limit the number of instance creation
It is just an enhancement to Singleton Design Pattern
By making our constructor private and then creating a visible constructor method, we can limit the number of instance creations (like we do in singleton design pattern) or recycle instances or other construction-related tasks.
new x()
null
null
public class LimitObjectCreationTest { public static void main(String[] args) { LimitClass obj; int i=1; while(i<=20) { obj = LimitClass.getLimInstance(); i++; } } } class LimitClass { /** * count of alive instances in JVM */ public static int objCount = 0; /** * private constructor * increases the objCount static variable on every object creation */ private LimitClass(){ objCount++; System.out.println("instance " + objCount + " created"); } /** * static factory method to return LimitClass instance * @return instance of LimitClass if not reached to threshold, else returns null */ public static synchronized LimitClass getLimInstance() { if(objCount < 3 ){ return new LimitClass(); } System.out.println("Instance Limit reached. Can not create new Object"); System.gc(); return null; } /** * decreases the objCount static variable when JVM runs garbage collection * and destroys unused instances */ @Override public void finalize() { System.out.println("Instance destroyed"); objCount--; } }
Download Complete Java Program »
output:
instance 1 created instance 2 created instance 3 created Instance Limit reached. Can not create new Object Instance Limit reached. Can not create new Object Instance destroyed Instance Limit reached. Can not create new Object Instance destroyed instance 3 created Instance destroyed instance 2 created instance 3 created Instance Limit reached. Can not create new Object Instance Limit reached. Can not create new Object Instance destroyed Instance Limit reached. Can not create new Object Instance destroyed instance 3 created Instance destroyed instance 3 created instance 3 created Instance Limit reached. Can not create new Object Instance Limit reached. Can not create new Object Instance destroyed Instance Limit reached. Can not create new Object Instance destroyed Instance destroyed instance 1 created instance 2 created
3) To give meaningful name using static factory method
As mentioned in Effective Java by Joshua-Bloch, one advantage of static factory methods is that, unlike constructors, they have names.
If the parameters to a constructor do not describe the object being returned, a static factory with a well-chosen name is easier to use and the resulting client code easier to read.
For example, the BigInteger(int, int, Random)
BigInteger
that is probably
BigInteger.probablePrime()
In other words, a private constructor allows you to provide factory methods whose names are more private
ensures that people use only the more self-evident names.
4) Static Utility Class or Constant Class
Static Utility Class
Think of a scenario when you have a class full of utility functions. Instantiating an instance of it makes no semantic sense, but you still want to call its methods.
What is the best way to deal with this?
- declare your class final, so that no one can extend it
- declare its constructor private (for not allowing instance creation)
- provide public static utility methods
java.util.Collections
public class Collections { // Suppresses default constructor, ensuring non-instantiability. private More ...Collections() { } // constants and utility methods }
Other JDK implementation of Utility classes
Constant Class
If our application has lots of constants, we can create final
private
constructor similar to what we do in static
static
method list down all your constant over there.
final class MyConstant { public static final String C1= "foo"; public static final String C2 = "bar"; } public static void main(String[] args) { if("foo".equals(MyConstant.C1)) { // To Do } }
With the introduction of typesafe enums in Java5, it is not good practice to use constant class anymore.
5) To Prevent Subclassing
We can prevent super()
final
class.
For Example, If we try to compile below code,
class A { private A() { } } class B extends A { }
It is class
final
Point to be note here is that, we can not declare
abstract
class asfinal
, but we can createabstract
class having onlyprivate
constructor.
What is the use of declaring
Well, here are some of the logical
-
though we can not create
instance of a class, we can still us that abstract class as static utility class or constant class. -
There is another use case, quite rare though: you can have
an abstract class
with onlyprivate
constructors thatcontains its own subclasses as nested classes. This idiom makes sure those nested classes are the only subclasses. In fact,enum
s in Java use just this idiom.
6) Builder Design Pattern
Private constructors are also used in Builder Design Pattern and thus creating Immutable classes as well.
For more details on this, you can go through our articles Builder Design Pattern and How To Create Immutable Class In Java
That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.
Happy Learning 🙂
If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.
We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.
About the Author
Tags: Collections, Core Java, Creational Design Patterns, Design Patterns, Java, Java keywords
Comments and Queries
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:<pre><code class="java"> String foo = "bar"; </code></pre>For more information on supported HTML tags in disqus comment, click here.