Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

singleton class

 
Mohan Ramanna
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello friends,
I know that a singleton class is one which can have only one
instance.
I wanted to know how to make a class singleton.
thanks in advance
bye bye
-regards
mohan
 
lakshmi nair
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
One way to acheive this is to make the constructor private and provide a public creator function(theInstance in code). The class will also have a static var of its own type.
When we call theInstance(), it returns this static instance of the class. if the variable is null(i.e., just the first time) then a new object is created. From the next time onwards the same instance is returned.
See code below...
Hope this helps
Regards,
Lakshmi
 
Mohan Ramanna
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot Lakshmi,
I got the concept it is very clear now.I tird the code also.
But i would like to ask u where do we find this singleton class to be useful.
Thanks a lot.
bye
regards
-mohan
 
Adrian Yan
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Singleton classes are very useful especially in web development. You can use singleton classes to share things such as connection pool.
Also, sometime, you just want to have a signle instance of a class, that means you can use singleton.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A singleton class is used when it only makes sense to have one instance of a class. The Runtime class in java is an example of a singleton class. Or perhaps you have a space simulator and you have a class Universe to represent the Universe, it only makes sense to have one instance (unless you get into multiple-dimensions etc. but that's missing the point ;-) )
------------------
*************************
When I was your age, I was twenty.
 
Dev Prakash
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi lakshmi,
I guess in your code the method "theInstance" should be static, so that other class can you this class to create the new instance or use the available instance.
- dev Prakash
 
lakshmi nair
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops!!! sorry for the carelessness on my side!!!
The method must be static...
lakshmi nair
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic