What is singleton? 1 Answer(s) 2 years and 8 months ago
Posted in : Java Beginners
Hi,
I want to know more about the singleton in Java. Please explain me what is singleton in Java? Give me example of Singleton class.
Thanks
View Answers
October 5, 2010 at 4:50 PM
hello, Singleton is a concept in which you can create only object of a class. You can achive this features by making class constructor private, and write a single static method (single entry) for object creation. ex. public class SingletonExample{ public static SingletonExample obj= null; private SingletonExample(){ } public static SingletonExample getClassObj(){ if(obj == null){ obj = new SingletonExample(); } return obj; }
} Test class public class test{ public static void main(String arg[]){ System.out.println(SingletonExample.getClassObj().toString); System.out.println(SingletonExample.getClassObj().toString); } }