- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Private Constructors and Singleton Classes in Java Programming
As we know the primary role of the constructor is to instantiate a class object now if we made the constructor as private then we restrict its calling to be only in defining a class and not in some other class.
Now the singleton class in Java is defined as the class which restricts the instantiation of a class and ensure that only one instance of the class exists in the JVM. After first time if instantiate the singleton class the new variable also points to the first instance created.
In order to create a singleton class we could use the concept of the private constructor as it also restricts the instantiation of class in defining class only. In singleton class, we use private constructor so that any target class could not instantiate our class directly by calling constructor, however, the object of our singleton class is provided to the target class by calling a static method in which the logic to provide only one object of singleton class is written/defined.
The designing of a singleton class is better explained by the following example.
Example
public class SingletonClassDriver { public static void main(String[] args) { SingletonClass obj = SingletonClass.getObject(); SingletonClass obj1 = SingletonClass.getObject(); System.out.println(obj); System.out.println(obj1); } } class SingletonClass { public static SingletonClass obj = null; private SingletonClass() { } public static SingletonClass getObject() { if (obj == null) { obj = new SingletonClass(); } return obj; } }
Output
SingletonClass@f6a746 SingletonClass@f6a746
To Continue Learning Please Login
Login with Google