Write a Java program to create a singleton class with method name as that of class


The Create_Singleton class contains the main() method, where three objects of the Singleton class are created using the Singleton() method. The purpose is to check whether all the objects are pointing to the same memory location or not.

The Singleton class has a private static reference singleRef of the Singleton class type. The constructor of the Singleton class is private, so it can't be accessed from outside of the class.

The Singleton() method is a public static method that returns an object of the Singleton class. In this method, we check whether the singleRef variable is null or not. If it's null, we create a new object of the Singleton class and assign it to the singleRef variable. Otherwise, we return the already created object.

In the Create_Singleton class, we check whether all the three objects created using the Singleton() method are pointing to the same memory location or not. If yes, it means the Singleton class is working as expected.

Source Code

class Create_Singleton
{
	public static void main(String args[])
	{
		Singleton o1 = Singleton.Singleton();
		Singleton o2 = Singleton.Singleton();
		Singleton o3 = Singleton.Singleton();
 
		if (o1 == o2 && o1 == o3)
		{
			System.out.println("All object are pointing to the same memory location.");
		}
		else
		{
			System.out.println("All object are not pointing to the same memory location.");
		}
	}
}
class Singleton
{
	private static Singleton singleRef = null;
 
	private Singleton() {}
 
	public static Singleton Singleton()
	{
		if (singleRef == null)
		{
			singleRef = new Singleton();
		}
		return singleRef;
	}
}

Output

All object are pointing to the same memory location.