![]() |
VOOZH | about |
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.
The 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.
The 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.
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.