How to call private constructors in Java?

Private constructors cannot be called directly because they can only be called from within the class. In general, private constructors are used to restrict the instantiation of a class, often paired with static public methods or static factory methods to create instances of the class. This ensures that objects can only be created through specific methods, allowing for control and management of the objects.

Below is an example code that demonstrates how to call a private constructor through a static public method within a class:

public class MyClass {
    private MyClass() {
        // 私有构造方法
    }

    public static MyClass getInstance() {
        return new MyClass();
    }
}

In the above code, the private constructor MyClass() is declared as private, preventing outside access. Instead, the class instance is obtained through the public static method getInstance(), which internally calls the private constructor to create an object. This way, outsiders can only access an instance of MyClass through the getInstance() method, ensuring control and management of the object.

Example of usage:

MyClass obj = MyClass.getInstance();

By utilizing the method mentioned above, we can create objects by calling private constructors from outside the class.

bannerAds