In this article we learn the what is singleton class in java with example.
What is Singleton Class in Java?
A Singleton class in Java allows only one instance to be created and provides global access to all other classes through this single object or instance.
The primary purpose of Single class is to restrict the limit of the number of object creation to only one. This often ensures that there is access control to resources, for example, socket or database connection.
The memory space wastage does not occur with the use of singleton class because it restricts the instance creation.
Firstly, declare the constructor of the Singleton class with the private keyword. We declare it as private so that no other classes can instantiate or make objects from it.
A private static variable of the same class that is the only instance of the class.
Use a static method that has return type object of this singleton class.
We can’t create more than one object of class.
Singleton Class in Java Example
class parent2{
int a=20;
private parent2() {
}
public static parent2 returnparen2object () {
parent2 obj=new parent2();
return obj;
}
}
public class SingleTonEx1 {
public static void main (String [] args) {
parent2 obj=parent2.returnparen2object (); // new object
System.out.println(“obj. A1=”+obj. a); obj. a=500;
System.out.println(“Obj.A2=”+obj.a);
parent2 obj1=parent2.returnparen2object (); // new object
System.out.println(“Obj.A3=”+obj1.a);
}
}
Output:
obj. A1=20
Obj.A2=500
Obj.A3=20