InterviewSolution
| 1. |
What is a singleton class in Java? And How to implement a singleton class? |
|
Answer» Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed. Understand this with the help of an example-: Consider the water jug in the office and if every employee wants that water then they will not create a NEW water jug for drinking water. They will use the existing one with their own reference as a glass. So programmatically it should be implemented as - class WaterJug{ PRIVATE int waterQuantity = 500; private WaterJug(){} private WaterJug object = null; // Method to provide the service of Giving Water. PUBLIC int getWater(int quantity){ waterQuantity -= quantity; return quantity; } // Method to return the object to the user. public static Waterjug getInstance(){ // Will Create a new object if the object is not ALREADY created and return the object. if(object == null){ object = new WaterJug(); } return object; }}In the above class, the Constructor is private so we cannot create the object of the class. But we can get the object by CALLING the method getInstance(). And the getInstance is static so it can be called without creating the object. And it returns the object. Now with that object, we can call getWater() to get the water. Waterjug glass1 = WaterJug.getInstance();glass1.getWater(1);We can get the single object using this getInstance(). And it is static, so it is a thread-safe singleton class. Although there are many ways to create a thread-safe singleton class. So thread-safe classes can also be:
|
|