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:
3rd Jul, 2024
Views
Read Time
12 Mins
share image icon
In this article
Chevron in toc
View All
Private Constructor in Java: Use Cases Explained with Example

In Java programming, understanding the intricacies of class design and object creation is crucial for developers aiming to excel in their careers. Among these intricacies, the concept of a Private Constructor in Java emerges as a fundamental aspect that piques the curiosity of many aspiring to master the language. Through years of coding and project development, I’ve come to value the nuances and advantages of using private constructors in Java applications. This introduction is your doorway to grasping the what, why, and how of private constructors.

From enhancing encapsulation to implementing singleton design patterns, private constructors offer unique advantages in Java. I aim to share insights from real-world applications, clarifying how private constructors can be employed to forge more secure and well-organized code. This article is intended for professionals seeking to expand their Java knowledge, encompassing key topics such as the definition of a private constructor, its governing rules, and its practical applications. We will conclude by highlighting the importance of private constructors in Java development, providing a thorough understanding of their role in creating robust and maintainable code.

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

Explore Our Software Development Free Courses

What is a Private Constructor?

In my journey as a software developer, I’ve often encountered scenarios where the concept of a Private Constructor in Java proved to be a game-changer. A private constructor is a particular type of constructor in Java designed to restrict the instantiation of a class from outside its own boundary. This means with a java class with private constructor, you cannot create an object of this class from any other class. 

Ads of upGrad blog

Why use it, you might ask? Throughout my career, I’ve leveraged private constructors in several use cases, such as creating utility classes where static methods and fields need not be associated with any particular object. For instance, consider a utility class that provides mathematical operations. By making its constructor private, we ensure that no one can create an example of this class, maintaining its purpose as a pure utility provider without any instantiation overhead. Using a private constructor, we enforce this uniqueness, preventing any other class from creating another instance. 

What is the purpose of a Private Constructor in Java?

A private constructor in Java serves multiple essential purposes. Firstly, it restricts the instantiation of a class to within the class itself, preventing external code from creating instances directly. This is particularly useful for enforcing design patterns such as Singleton, where only one instance of a class should exist throughout the application’s lifecycle. By controlling object creation internally, private constructors ensure that the class adheres to specific initialization logic, maintaining consistency and integrity in its state.

Secondly, private constructors are utilized in utility classes that provide helper methods and constants but do not require instantiation. This approach promotes efficient and organized code structure by centralizing functionality without the overhead of object creation. Such classes often house static methods for tasks like mathematical computations, file operations, or configuration management, offering reusable functionalities without the need to instantiate objects. Overall, private constructors contribute significantly to encapsulation by confining object creation details within the class, thereby enhancing code reliability and promoting best practices in Java development.

What are the Rules for Private Constructors?

In my years of experience as a Java developer, I’ve encountered several scenarios where using a Private Constructor in Java was beneficial and essential. Let me share some rules and insights on this topic based on real-life applications and their impact.  

  • Singleton Pattern Implementation: The most common use case for a “Private Constructor in Java” is in the Singleton design pattern. Here, ensuring that a class has only one instance requires that the constructor be private. This control mechanism prevents any other class from instantiating it directly. 
  • Utility Classes: For classes that serve purely as collections of static methods and static variables, making the constructor private prevents instantiation. It’s a practical approach I’ve employed in numerous projects to signify that the class is a utility holder. 
  • Factory Method Pattern: In scenarios where classes are designed with factory methods responsible for object creation, private constructors restrict instantiation to within the class itself. This technique ensures that object creation is controlled and can be modified without affecting external code. 
  • Controlling Access: The private constructor in Java access rule is pivotal in controlling how other classes interact with the constructor. It effectively limits access to the constructor, thereby guiding the use of the class in a predefined manner. Understanding how to access private constructor in Java involves defining a public static method within the class that calls the private constructor, ensuring that object instantiation follows specific guidelines set by the class design.
  • Extending Classes: It’s worth noting that a class with a private constructor cannot be subclassed. This rule is particularly useful when creating immutable classes or ensuring that the integrity of the class hierarchy is maintained without unexpected subclassing. 

Incorporating private constructors in Java, based on these rules, has significantly influenced the design and functionality of the applications I’ve worked on. 

What are the Use Cases of Private Constructor in Java?

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)

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.

Here are some private constructor in java with examples:

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 3: 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

Ads of upGrad blog

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, I have 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.

Check out all the Trending Java Tutorial Topics in 2024.

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.

4What is public and private in constructor?

In Java, a public constructor allows any part of the program to create instances of a class freely, providing unrestricted access to object creation. Conversely, a private constructor restricts instance creation to within the class itself, used to control how and when objects are created, as seen in Singleton patterns or utility classes that should not be instantiated.

5Can a class with private constructor be inherited in Java?

No, a class with a private constructor in Java cannot be inherited because the subclass cannot access the private constructor of its superclass, preventing it from calling the constructor to initialize the parent class.

6When to use public vs private in Java?

In Java, use the public access modifier for methods and variables when you want them accessible from any other class or package, allowing widespread use and interaction. On the other hand, employ the private access modifier to restrict access to methods and variables within the same class only, enhancing encapsulation by hiding implementation details and ensuring controlled, secure access to class internals.

7Can a constructor be private in C++?

Private constructor in C++ cannot be explicitly declared, unlike in some other languages like Java. However, you can achieve similar functionality by declaring a constructor as 'private' within the class declaration. This prevents external instantiation but allows controlled object creation through 'friend' functions or static member functions.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Full Stack Developer Salary in India in 2024 [For Freshers &#038; Experienced]
907173
Wondering what is the range of Full Stack Developer salary in India? Choosing a career in the tech sector can be tricky. You wouldn’t want to choose
Read More

by Rohan Vats

15 Jul 2024

SQL Developer Salary in India 2024 [For Freshers &#038; Experienced]
902296
They use high-traffic websites for banks and IRCTC without realizing that thousands of queries raised simultaneously from different locations are hand
Read More

by Rohan Vats

15 Jul 2024

Library Management System Project in Java [Comprehensive Guide]
46958
Library Management Systems are a great way to monitor books, add them, update information in it, search for the suitable one, issue it, and return it
Read More

by Rohan Vats

15 Jul 2024

Bitwise Operators in C [With Coding Examples]
51783
Introduction Operators are essential components of every programming language. They are the symbols that are used to achieve certain logical, mathema
Read More

by Rohan Vats

15 Jul 2024

ReactJS Developer Salary in India in 2024 [For Freshers &#038; Experienced]
902673
Hey! So you want to become a React.JS Developer?  The world has seen an enormous rise in the growth of frontend web technologies, which includes web a
Read More

by Rohan Vats

15 Jul 2024

Password Validation in JavaScript [Step by Step Setup Explained]
48975
Any website that supports authentication and authorization always asks for a username and password through login. If not so, the user needs to registe
Read More

by Rohan Vats

13 Jul 2024

Memory Allocation in Java: Everything You Need To Know in 2024-25
74111
Starting with Java development, it’s essential to understand memory allocation in Java for optimizing application performance and ensuring effic
Read More

by Rohan Vats

12 Jul 2024

Selenium Projects with Eclipse Samples in 2024
43491
Selenium is among the prominent technologies in the automation section of web testing. By using Selenium properly, you can make your testing process q
Read More

by Rohan Vats

10 Jul 2024

Top 10 Skills to Become a Full-Stack Developer in 2024
229995
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

10 Jul 2024

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