Write a program in Java to demonstrate the use of private constructor and also write a method which will count the number of instances created using default constructor only.

Here's an example Java program that demonstrates the use of a private constructor and a method to count the number of instances created using the default constructor: 

Create a Example.java file and write this code in it.

public class Example {
    private static int instanceCount = 0;

    // Private constructor
    private Example() {
        instanceCount++;
    }

    // Public static method to get instance count
    public static int getInstanceCount() {
        return instanceCount;
    }

    public static void main(String[] args) {
        // Create a new Example object using the private constructor
        // This will not be counted in the instance count
        Example example1 = new Example();

        // Create a new Example object using the default constructor
        // This will be counted in the instance count
        Example example2 = new Example();

        // Create a new Example object using the default constructor
        // This will also be counted in the instance count
        Example example3 = new Example();

        // Print the instance count
        System.out.println("Instance count: " + Example.getInstanceCount());
    }
}


In this example, we have a Example class with a private constructor that increments a static instanceCount variable each time a new instance of the class is created using the default constructor. We also have a public static method that returns the instance count.

In the main() method, we create three Example objects using the private constructor and the default constructor. We then print the instance count to the console using the getInstanceCount() method.

Note that the first Example object created using the private constructor will not be counted in the instance count, since it was created using a private constructor and cannot be accessed outside the class. The other two Example objects created using the default constructor will be counted in the instance count.

Comments