Yes, Java allows constructors to be declared as private. A private constructor prevents objects of the class from being created outside the class itself. This technique is commonly used to control object creation and enforce specific design patterns.
Key Points: • A private constructor restricts object creation from outside the class. • It is commonly used in the Singleton Design Pattern to ensure only one instance exists. • Utility classes that contain only static methods often use private constructors to prevent instantiation. • Private constructors provide better control over object creation. • They are useful when object creation must be managed through factory methods.
Example: The Singleton pattern uses a private constructor to ensure that only one object of the class can be created and shared throughout the application.
Code Example:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
System.out.println("Singleton Object Created");
}
public static Singleton getInstance() {
return instance;
}
public static void main(String[] args) {
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
System.out.println(obj1 == obj2);
}
}Output:
Singleton Object Created true
Another Common Use Case:
public class MathUtil {
private MathUtil() {
}
public static int add(int a, int b) {
return a + b;
}
}In this example, no object of MathUtil can be created because all functionality is provided through static methods.
Interview Tip: A concise interview answer is:
"Yes, a constructor can be private in Java. A private constructor prevents object creation from outside the class and is commonly used in Singleton classes, utility classes, and factory-based object creation patterns where controlled instantiation is required."