InterviewSolution
Saved Bookmarks
| 1. |
How to make a class Singleton |
|
Answer» SINGLETON class is a class which has only a single object. This means you can instantiate the class only once.When we declare the constructor of the class as private, it will limit the scope of the creation of the object.If we return an INSTANCE of the object to a static METHOD, we can handle the object creation inside the class itself. We create a static block for the creation of an object. For example, PUBLIC class Example { private static Example obj; static { obj = new Example(); // creation of object in a static block } private Example() { } // declaring the constructor as private public static Example getObject() { return obj; } public void print() { System.out.println("Just for checking"); } public static void main(String[] args) { Example e = getObject(); e.print(); } } |
|