Syntax error What is the purpose of private constructor in Java?

What is the purpose of private constructor in Java?



In this article, we will learn about the purpose of private constructor in Java. Constructor is a unique method used to initialize objects. Constructors are public or protected by default, which allows outside classes to create instances

Why Use a Private Constructor?

Private constructor is mainly applied to manage object creation. It does not allow other classes to instantiate the class, creating particular design patterns or restrictions.

Purpose of a Private Constructor

The private constructor is useful in case we want to restrict the object creation. For example ?

  • Singleton pattern can be implemented using a private constructor.
  • Utility classes prevent the instantiation of classes that contain only static methods.
  • Factory methods control object creation by static methods instead of constructors.

Singleton Pattern Using a Private Constructor

The Singleton Pattern ensures that a class has only one instance and provides a global access point to that instance.

The following are the steps to create a singleton pattern using a private constructor ?

  • Private Constructor (private Tester()): Prevents direct object creation using new Tester().
  • Static Instance Variable (private static Tester instance): Holds the single instance of the class.
  • Static Method (getInstance()): Returns the existing instance if already created and creates a new instance only if instance == null (first call).
  • Checking Singleton Property: Two calls to getInstance() return the same object, so tester.equals(tester1) prints true.

Example

Below is an example of creating a singleton pattern using a private constructor in Java ?

public class Tester {
   private static Tester instance;
   private Tester(){}
 
   public static Tester getInstance(){
      if(instance == null){
         instance = new Tester();
      }
      return instance;
   }
 
   public static void main(String[] args) {
      Tester tester = Tester.getInstance();
      Tester tester1 = Tester.getInstance();
      System.out.println(tester.equals(tester1));
   }  
}

Output

true

Time complexity: O(1), constant time object retrieval or creation.
Space complexity: O(1), since only a single instance of Tester is stored.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-03-26T12:05:52+05:30

873 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements