Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconPrivate Constructor in Java: Use Cases Explained with Example

Private Constructor in Java: Use Cases Explained with Example

Last updated:
9th Apr, 2021
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
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.   

Check out our free courses to get an edge over the competition.

Explore Our Software Development Free Courses

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.

Check Out upGrad Full Stack Development Bootcamp (JS/MERN)

Ads of upGrad blog

Explore our Popular Software Engineering Courses

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

Check Out upGrad Advanced Certification in DevOps

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.

Our learners also read: Free java course!

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.

In-Demand Software Development Skills

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.

Ads of upGrad blog

Instance number 5 is created.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Read our Popular Articles related to Software Development

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 Executive PG Program in Full Stack Development course that is designed for working professionals to gain expertise in this area.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What are constructors in programming?

Constructors in programming are the methods that are called automatically when an object is initialized. The constructor's purpose is to initialize the object. Constructors should always be public and they are declared without any return type. Constructors are used to initialize the object and to perform other tasks that can be done only once. Constructors are also used to perform initialization of a class, that is, to perform tasks that create the class.

2What are the types of constructors in Java?

There are five types of constructors in Java. They are: No-argument constructors: It has a default implementation, which is executed when the class is loaded into the memory. A class which has no no-argument constructor MUST be declared as final. Default constructors: This constructor is created when the class is written in Java and is used to initialize all the class's variables (attributes) to their default values (zero or null). Parameterized constructors: This constructor is used to initialize some variables from some values. Constructors with no return value: It is used to initialize some variables from some values. Constructors with return value: it is used to initialize some variables from some values and also returns with a value.

3What is a private constructor in Java?

Private constructors can be used to create an immutable class. Without using private constructors, we can create immutable classes by declaring the class final and creating all the attributes as final (e.g. private final String name;). A private constructor cannot be directly called by client objects of the class. They can only be called internally by methods of the class (even private). You can have a private constructor with one or more parameters. You cannot have return type of the constructor be primitive boolean. It can be either String or Class.

Explore Free Courses

Suggested Blogs

Top 40 MySQL Interview Questions &#038; Answers For Beginners &#038; Experienced [2023]
118095
Have a Data engineering or data science interview coming up? Need to practice some of the most asked MySQL interview questions? The article compiles t
Read More

by Rohan Vats

07 Nov 2023

Literals In Java: Types of Literals in Java [With Examples]
5969
Summary: In this article, you will learn about Literals in Java. Literals in Java Integral Literals Floating-Point Literals Char Literals String Lit
Read More

by Rohan Vats

29 Oct 2023

10 Interesting HTML Project Ideas &#038; Topics For Beginners [2023]
392907
Summary In this article, you will learn 10 Interesting HTML Project Topics. Take a glimpse below. A tribute page A survey form Technical documentati
Read More

by Rohan Vats

04 Oct 2023

15 Exciting SQL Project Ideas &#038; Topics For Beginners [2023]
285341
Summary: In this Article, you will learn 15 exciting SQL project ideas & topics for beginners. Library Management System Centralized College Dat
Read More

by Rohan Vats

24 Sep 2023

17 Interesting Java Project Ideas &#038; Topics For Beginners 2023 [Latest]
35386
Summary: In this article, you will learn the 17 Interesting Java Project Ideas & Topics. Take a glimpse below. Airline reservation system Data v
Read More

by Rohan Vats

24 Sep 2023

9 Exciting Software Testing Projects &#038; Topics For Beginners [2023]
8319
Software testing might constitute 50% of a software development budget but it is viewed as a lethargic and unnecessary step by most students. Even edu
Read More

by Rohan Vats

21 Sep 2023

Top 10 Skills to Become a Full-Stack Developer in 2023
218264
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

21 Sep 2023

Java Free Online Course with Certification [2023]
57066
The PYPL Popularity of Programming Language Index maintains that Java is the second most popular programming language in the world, after Python.  Alt
Read More

by Rohan Vats

20 Sep 2023

Salesforce Developer Salary in India in 2023 [For Freshers &#038; Experienced]
903234
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

20 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon