- 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
Can we declare a constructor as private in Java?
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.
Conditions for Private Constructor
- A private constructor does not allow a class to be subclassed.
- A private constructor does not allow to create an object outside the class.
- If all the constant methods are there in our class we can use a private constructor.
- If all the methods are static then we can use a private constructor.
- If we try to extend a class which is having private constructor compile time error will occur.
Example
class SingletonObject { private SingletonObject() { System.out.println("In a private constructor"); } public static SingletonObject getObject() { // we can call this constructor if (ref == null) ref = new SingletonObject(); return ref; } private static SingletonObject ref; } public class PrivateConstructorDemo { public static void main(String args[]) { SingletonObject sObj = SingletonObject.getObject(); } }
Output
In a private constructor
Advertisements