- 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
What is the purpose of private constructor in Java?
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.
Example
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
It will print the output as
true
Advertisements