How can we create this singleton class?

A Singleton class can be created by restricting object creation and ensuring that only one instance of the class exists throughout the application. This is achieved by making the constructor private, creating a static instance of the class, and providing a public static method to access that instance.

Key Points: • The constructor is declared private to prevent object creation using the new keyword. • A private static variable holds the single instance of the class. • A public static method provides global access to the instance. • Singleton ensures controlled access to shared resources. • It is commonly used for configuration managers, loggers, caches, and database connection managers.

Steps to Create a Singleton Class:

1. Declare the constructor as private. 2. Create a private static instance of the class. 3. Provide a public static method to return the instance. 4. Prevent direct object creation from outside the class.

Example: A configuration manager should have only one instance so that all modules use the same configuration data throughout the application.

Code Example:

public class Singleton {

    private static Singleton instance;

    private Singleton() {
    }

    public static Singleton getInstance() {

        if (instance == null) {
            instance = new Singleton();
        }

        return instance;
    }
}

public class Demo {

    public static void main(String[] args) {

        Singleton obj1 = Singleton.getInstance();
        Singleton obj2 = Singleton.getInstance();

        System.out.println(obj1 == obj2);
    }
}

Output:

true

Advantages: • Ensures only one object exists • Saves memory and system resources • Provides a centralized access point • Useful for shared application services

Interview Tip: A concise interview answer is:

"To create a Singleton class, make the constructor private, create a private static instance of the class, and provide a public static method that returns that instance. This ensures that only one object of the class is created and shared throughout the application."