Home Answers Viewqa Java-Beginners What is singleton?

 
 


Deepak Kumar
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);
}
}

o/p both print same string representation of obj

Let me know if u have any doubt on this.
Thanks









Related Pages:

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.