Member-only story
Can a Java Constructor Be private? The Interviewer Wanted More Than Yes or No.
Can a constructor in Java be private?
Yes, it can.
Java allows us to declare a constructor as private, which prevents code outside the class from invoking it directly.
But why would we need a private constructor? If another class cannot call it, how do we create an object? And if we can still create objects from inside the class, what problem does making the constructor private actually solve?
Let’s start with a simple example.
class Employee {
private Employee() {
System.out.println("Employee created");
}
}Now try creating an object from another class:
Employee employee = new Employee();The compiler rejects this code because the constructor is private.
Friend link
Does that mean nobody can create an object of Employee?
Not exactly. Code inside the Employee class can invoke its own private constructor. We can also expose a public static factory method that creates and returns an instance.
class Employee {
private Employee() {
System.out.println("Employee created");
}
public static…







