Java program to implement private constructors

In Java, we can declare a constructor as private to prevent the creation of objects of that class by other classes. A private constructor is typically used in a singleton design pattern, where we ensure that only one instance of the class is created throughout the application. Here's an example Java program to implement a private constructor:

‮efer‬r to:theitroad.com
public class PrivateConstructorExample {
    private static PrivateConstructorExample instance = null;

    private PrivateConstructorExample() {
        // Private constructor
    }

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

    public void printMessage() {
        System.out.println("Hello, World!");
    }
}

In this program, we have a PrivateConstructorExample class with a private constructor. We have also declared a static variable instance to hold the single instance of the class. We use a static method getInstance() to get the single instance of the class. In this method, we check if the instance is null and create a new instance if it's null. We return the instance from this method.

We have also added a printMessage() method to print a message to the console. We can call this method on the single instance of the class.

Here's an example usage of the PrivateConstructorExample class:

public class Main {
    public static void main(String[] args) {
        PrivateConstructorExample obj1 = PrivateConstructorExample.getInstance();
        obj1.printMessage();
        PrivateConstructorExample obj2 = PrivateConstructorExample.getInstance();
        obj2.printMessage();
        System.out.println(obj1 == obj2); // Output: true
    }
}

In this usage example, we first create an instance of the PrivateConstructorExample class using the getInstance() method. We then call the printMessage() method on this instance. We create a second instance of the class using the getInstance() method and call the printMessage() method on this instance as well. We also compare the two instances using the == operator and print the result to the console. Since both instances are the same object, the output of this comparison is true.