Last Updated : 23 Jul, 2025
In Java, the private constructor is a special type of constructor that cannot be accessed from outside the class. This is used in conjunction with the singleton design pattern to control the instantiation.
Private ConstructorThe private constructor is used to resist other classes to create new instances of the class. It can be only accessed within the class. These are used to create singleton design patterns such as in Math class. private constructors are used in different scenarios such as Internal Constructor chaining and Singleton class design patterns.
Singleton ClassesThe Singleton pattern is a design pattern that is used to ensure that the class has only one instance which can be possible using the private constructor. In a singleton design pattern, there is a global point access which is used to access the classes and their properties. The private constructor is the main characteristic of singleton design in Java.
The constructor of the singleton class would be private so there must be another way to get the instance of that class. This problem is resolved using a class member instance and a factory method to return the class member.
characteristic
Example: Implementing the singleton design pattern using the private constructor.
Java
// Java program to demonstrate implementation of Singleton
// pattern using private constructors.
import java.io.*;
class MySingleton
{
static MySingleton instance = null;
public int x = 10;
// private constructor can't be accessed outside the class
private MySingleton() { }
// Factory method to provide the users with instances
static public MySingleton getInstance()
{
if (instance == null)
instance = new MySingleton();
return instance;
}
}
// Main Class
class Geeks
{
public static void main(String args[])
{
MySingleton a = MySingleton.getInstance();
MySingleton b = MySingleton.getInstance();
a.x = a.x + 10;
System.out.println("Value of a.x = " + a.x);
System.out.println("Value of b.x = " + b.x);
}
}
Value of a.x = 20 Value of b.x = 20
Explanation: The above program makes sure that only one instance of the MySingleton class is created with the help of a private constructor. Here we changed the value of a.x, value of b.x also got updated because both ‘a’ and ‘b’ refer to the same object, i.e., they are objects of a singleton class.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4