Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners What is singleton?
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


Deepak Kumar
What is singleton?
1 Answer(s)      4 years and a month 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

Advertisement
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 Tutorials/Questions & Answers:
Advertisements
Advertisements
 

 

 

DMCA.com