Private Constructor in Java: Use Cases Explained with Example

Introduction

A private constructor in Java is used in restricting object creation. It is a special instance constructor used in static member-only classes. If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.   

Private Constructor Use-Cases

Private constructors in Java are accessed only from within the class. You cannot access a private constructor from any other class. If the object is yet not initialised, then you can write a public function to call the private instructor. If the object is already initialised, then you can only return the instance of that object. A private constructor in Java has the following use-cases:

  • You can use it with static members-only classes.
  • You can use it with static utility or constant classes.
  • You can use it to serve singleton classes.
  • You can use it to assign a name, for instance, creation by utilising factory methods.
  • You can use it to prevent subclassing.

Singleton Class

The private constructor in Java is used to create a singleton class. A singleton class is a class in Java that limits the number of objects of the declared class to one. A private constructor in Java ensures that only one object is created at a time. It restricts the class instances within the declared class so that no class instance can be created outside the declared class. You can use the singleton class in networking and database connectivity concepts.

Example 1: The following example demonstrates how a private constructor in Java limits the number of objects in a singleton class.

import java.io.*;

class newTestClass {

static newTestClass object = null;

public int a = 20;

private newTestClass() {

}

//we have created a private constructor

static public newTestClass displayInstance()

/**

*displayInstance() is a public method that we will use to create instance.

*Call this method to access these instances from outside the class.

*/

{

if (object == null)

     object = new newTestClass();

     //singleton class object is created

     return object;

}

}

public class SingletonClass {

public static void main(String args[]) {

     newTestClass instance1 = newTestClass.displayInstance();

     //displaying the instance of the singleton class by calling the public method

    newTestClass instance2 = newTestClass.displayInstance();

    //displaying the instance of the singleton class by calling the public method

    instance1.a = instance1.a + 26;

    System.out.println(“Instance 1 created has the following value = ” + instance1.a);

    System.out.println(“Instance 2 created has the following value = ” + instance2.a);

}

}

Output

Instance 1 created has the following value = 46

Instance 2 created has the following value = 46

In the above program, the value of instance 2 automatically gets updated when we update the instance1 object value. This observation demonstrates that both instance1 and instance 2 refer to the same object.

Example 2: The following example demonstrates how a private constructor in Java ensures that no more than one object is created at a time.

// Java program for a singleton class implementation

Import java.io.*;

public class newTestClass {

   private static newTestClass var=null;

   private newTestClass(){

   //Private Constructor can be accessed within the class

   }

   public static newTestClass testObject(){

           // This method ensures that only one object is created at a time

           if(var==null){

           var= new newTestClass();

           }

     return var;

   }

   public void display(){

           System.out.println(“This is an example of a Private constructor using a Singleton class. “);

   }

   public static void main(String args[]){

           newTestClass newObject= newTestClass.testObject();

           newObject.display();

   }

}

Output

This is an example of a Private constructor using a Singleton class.

Example 2: Private Constructor in Java to limit the number of class instances.

This example demonstrates how you can limit the number of class instances by declaring a constructor private.

public class restrictInstanceCreationClass {

           public static void main(String[] args) {

                          RestrictInstance obj;

                          int a=1;

                          while(a<=20)

                          {

                                        obj = RestrictInstance.getLimInstance();

                                        a++;

                          }

           }

}

class RestrictInstance {

           public static int varCount = 0;

           /**

           *create private constructor that increases the count

           *of varCount variable after each instance creation

           */

           private RestrictInstance() {

                          varCount++;

                          System.out.println(“Instance number ” + varCount + ” is created.”);

           }

          

           public static synchronised RestrictInstance getLimInstance() {

                          if(varCount <5) {

                                        return new RestrictInstance();

                          }

                          System.out.println(“Maximum instance limit reached. You are not allowed to create anymore instances.”);

                          System.gc();

                          return null;

           }

           /**

           *delete the instance and decrease the count

           *of the varCount variable

           */

           public void finalise()

           {

                          System.out.println(“Instance is deleted.”);

                          varCount–;

           }}

Output

Instance number 1 is created.

Instance number 2 is created.

Instance number 3 is created.

Instance number 4 is created.

Instance number 5 is created.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Instance is deleted.

Instance is deleted.

Instance is deleted.

Instance is deleted.

Maximum instance limit reached. You are not allowed to create anymore instances.

Instance number 1 is created.

Instance number 2 is created.

Instance number 3 is created.

Instance number 4 is created.

Instance number 5 is created.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Maximum instance limit reached. You are not allowed to create anymore instances.

Instance is deleted.

Instance is deleted.

Instance is deleted.

Instance number 1 is created.

Instance number 2 is created.

Instance number 3 is created.

Instance number 4 is created.

Instance number 5 is created.

Conclusion

The code used in the article is only for explanatory purposes. You can modify the statements given in the examples as per your requirements. In this blog, we discussed how a private constructor in Java limits the number of objects in a singleton class.

You can try out the code to strengthen your Java constructor’s knowledge. If you want to gain an in-depth understanding of Java, check out the upGrad PG Diploma in Full Stack Development course that is designed for working professionals to gain expertise in this area.

Become a Full Stack Developer

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN SOFTWARE DEVELOPMENT
LEARN MORE

0 replies on “Private Constructor in Java: Use Cases Explained with Example”

×