Warning: Undefined array key "amp-addthis" in /home/tgagmvup/onlinestudy.guru/wp-content/plugins/addthis/backend/AddThisSharingButtonsFeature.php on line 101
lang="en-US"> Singleton class in java - onlinestudy.guru
Site icon onlinestudy.guru

Singleton class in java

Singleton class is a class which ensures that there is only one instance of the class is available throughout the JVM. It is know as Singleton class.

There are three characteristics of a Singleton class
1.Define a private constructor.
2. Define private and static instance
3. Define public and static method for the instance which allow access to instance.


/**
 * singleton class ensures that there is
 * only one instance of the class is available inside the jvm
 */
public class Singleton {

    //characteristic of the singleton class
    //1. private constructor so that no one can create object

    private Singleton() {

    }

    //2. static instance
    private static Singleton instance;

    //3. static method for access

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