Sobes.tech
Junior — Middle

How does a declared private constructor behave when creating an instance of a class?

sobes.tech AI

Answer from AI

In Java, if a constructor is declared as private, it means that it is only accessible within the class itself and cannot be called from outside to create instances.

This approach is often used for:

  • Implementing the Singleton pattern, where it is necessary to ensure that a class has only one instance.
  • Creating factory methods within the class that control the process of object creation.

Example:

public class Singleton {
    private static Singleton instance;

    private Singleton() {
        // private constructor
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

In this example, attempting to create an object via new Singleton() outside the class will result in a compile-time error because the constructor is private. Creating an instance is only possible through the static method getInstance().