Sobes.tech
Junior — Middle

Why is it recommended to declare a class constructor as private in some cases?

sobes.tech AI

Answer from AI

Declaring a class constructor as private in Java is used to control the creation of class instances. Main reasons:

  • Restrict object creation: prevents creating instances from outside the class.
  • Implement Singleton pattern: guarantees that the class has only one instance.
  • Factory methods: the class can provide static methods to create objects with additional logic.
  • Utility classes: classes with a set of static methods where creating instances is unnecessary.

Example of Singleton with a private constructor:

public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {
        // private constructor
    }

    public static Singleton getInstance() {
        return instance;
    }
}

Here, the private constructor prevents direct instantiation, and access to the single instance is through the static method getInstance(). If immediate initialization after class definition is needed, a static block or direct initialization of instance can be used.