Singleton Class in Java

The class whose only one object can be created is called Singleton class. Now a days questions on Singleton class have become very common in interviews and other exams. So it is very important for every developer to have knowledge of Singleton class.

Features of Singleton class :

  1. Only one object can be created of singleton class.
  2. Singleton class contains a private constructor.
  3. To get object of singleton class we do not call a constructor but instead we call a static method which returns singleton class’ object.

Let us look at the code of Singleton class:

public class Tech4Humans {
	public static void main(String[] args) 
	{
		SingletonExample obj1 = SingletonExample.getSingObject();
		SingletonExample obj2 = SingletonExample.getSingObject();
		
		System.out.println("obj1 name before = "+obj1.greeting);
		System.out.println("obj2 name before = "+obj2.greeting);
		
		// changing the 'greeting' instance variable for obj1
		obj1.greeting="Bye Singleton";

		// change in greeting instance variable of obj1 will be 
		// reflected in obj2 which means both obj1 and obj2 point to same object 
		System.out.println("\nobj1 name after = "+obj1.greeting);
		System.out.println("obj2 name after = "+obj2.greeting);
	}
}

// Singleton class starts here
class SingletonExample
{
	static SingletonExample obj;
	String greeting;
	
	private SingletonExample() 
	{
		greeting="Hello Singleton";
	}
	
	static SingletonExample getSingObject() 
	{
		if(obj==null) 
		{
			obj= new SingletonExample();
		}
		return obj;
	}
}

Output

obj1 name before = Hello Singleton
obj2 name before = Hello Singleton

obj1 name after = Bye Singleton
obj2 name after = Bye Singleton

Observe the code carefully. On calling getSingObject() function for obj1 the ‘if’ condition will execute since obj1 is null for first time. ‘if‘ condition will call private constructor to assign it a new object of SingletonExample class.

Now obj2 calls getSingObject() function to get object of SingletonExample, but this time ‘if’ condition will not be executed, since obj variable is static and contains the object from previous call by obj1. So same old obj value will be returned.

Hence everytime we try to get an object of SingletonExample class then same old obj value will be returned. This can also be observed when we tried to change greeting variable of obj1. This change in greeting variable was also reflected in obj2. This implies both obj1 and ob2 points to same object.

Leave a Comment