Singleton Class Example in Java

Singleton is a class which has only one instance in whole application, it provides a public static method getInstance() to access the instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang. Runtime, java.awt.Desktop, java.awt.Toolkit etc.


Steps to create a Singleton class:

  • Create a private constructor to restrict instantiation of the class from other classes.
  • Create one private static instance of the class.
  • Create one public static method that returns the instance of the class.
class MySingletonClass {
	private static MySingletonClass mySingletonObj;

	// Create a private Constructor to prevents any other class from
	// instantiating
	private MySingletonClass() {
	}

	// Create a static instance to get the instance
	public static MySingletonClass getInstance() {
		if (mySingletonObj == null) {
			mySingletonObj = new MySingletonClass();
		}
		return mySingletonObj;
	}

	public void hello() {
		System.out.println("This is hello method from MySingletonClass");
	}
}

public class SingletonExample {
	public static void main(String[] args) {
		MySingletonClass st = MySingletonClass.getInstance();
		st.hello();
	}

}
						
Output
This is hello method from MySingletonClass


















Receive Latest Java Examples in Your Email: