Code Pumpkin

What is the use of private constructor in java?

Subscribe

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 inside declaring class.  By making a constructor private, we can prevent a class from being extended by any other class. 

Here are some of the uses of private constructor : 

  1. Singleton Design Pattern
  2. To limit the number of instance creation
  3. To give meaningful name for object creation using static factory method
  4. Static Utility Class or Constant Class
  5. To Prevent Subclassing
  6. Builder Design Pattern


1) Singleton Design Pattern

In Singleton design pattern, we restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.

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.

Doing new x() never returns null, but using the factory pattern, you can return null, or even return different subtypes.


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

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

output may vary based on your allocated JVM memory.


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.  

Immutable Class from Effective Java

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 constructor BigInteger(int, int, Random), which returns a BigInteger that is probably
prime, would have been better expressed as a static factory method named BigInteger.probablePrime().

In other words, a private constructor allows you to provide factory methods whose names are more understandable, and then making the constructor 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 is one of such utility class. Here is the initial few lines from it :


public class Collections {

     // Suppresses default constructor, ensuring non-instantiability.
     private More ...Collections() {
      }

     // constants and utility methods

}

Other JDK implementation of Utility classes

  1. java.util.Arrays
  2. java.lang.Math


Constant Class

If our application has lots of constants, we can create final class with private constructor similar to what we do in static utility class, but instead of providing 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.  Still its worth to know as many of legacy applications are still using it 🙂


5) To Prevent Subclassing

We can prevent sublcassing (extending). If we create only a private constructor, no class can extend your class, because it can't call the super() constructor. This is some kind of a alternative for final class.

For Example,  If we try to compile below code, compiler will give error saying Implicit super constructor A() is not visible for default constructor. Must define an explicit constructor


class A {
	private A() {
	}
}

class B extends A {
	
}

It is equilvalent to make our class A final.

Point to be note here is that, we can not declare abstract class as final, but we can create abstract class having only private constructor. 

What is the use of declaring private constructor in abstract class?

Well, here are some of the logical usecases.

  1. though we can not create instance of a class, we can still us that abstract class as static utility class or constant class.
  2. There is another use case, quite rare though: you can have an abstract class with only privateconstructors that contains its own subclasses as nested classes. This idiom makes sure those nested classes are the only subclasses. In fact, enums 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 can think of any more scenarios where we can use private constructor, feel free drop a comment. We would be happy to add that in our post. Thanks!

Tags: , , , , ,


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.

Total Post : 80
Subscribe
Contribute Your Articles

Interview Experiences

Related Books

Like Us On Facebook

Alexa Page Rank