Home »
Java Programs »
Java Class and Object Programs
Java program to create a singleton class with method name as that of class
Learn how to create a singleton class with method name as that of class in Java?
Submitted by Nidhi, on March 20, 2022
Problem statement
In this program, we will create a singleton class with a static method name as that of class. Here this method is not a constructor. It is used to implement a class as a Singleton.
Java program to create a singleton class with method name as that of class
The source code to create a singleton class with method name as that of the class is given below. The given program is compiled and executed successfully.
// Java program to create a singleton class with
// method name as that of class
class Singleton {
private static Singleton singleRef = null;
private Singleton() {}
public static Singleton Singleton() {
if (singleRef == null)
singleRef = new Singleton();
return singleRef;
}
}
class Main {
public static void main(String args[]) {
Singleton obj1 = Singleton.Singleton();
Singleton obj2 = Singleton.Singleton();
Singleton obj3 = Singleton.Singleton();
if (obj1 == obj2 && obj1 == obj3)
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.");
}
}
Output
All objects are pointing to the same memory location.
Explanation
In the above program, we created a singleton class Singleton and public class Main. The Singleton class contains a static method with a class name that returns the instance of the class.
The Main class contains a static method main(). The main() is an entry point for the program. Here, we created the instances obj1, obj2, obj3 and compared all objects, and printed the appropriate message.
Java Class and Object Programs »