Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes singleton class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "singleton class" Watch "singleton class" New topic

singleton class

Mohan Ramanna
Ranch Hand

Joined: Jun 26, 2000
Posts: 36
hello friends,
I know that a singleton class is one which can have only one
I wanted to know how to make a class singleton.
thanks in advance
bye bye
lakshmi nair
Ranch Hand

Joined: Oct 11, 2000
Posts: 63
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
Mohan Ramanna
Ranch Hand

Joined: Jun 26, 2000
Posts: 36
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.
Adrian Yan
Ranch Hand

Joined: Oct 02, 2000
Posts: 688
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.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Oct 09, 2000
Posts: 28
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

Joined: Oct 11, 2000
Posts: 63
Oops!!! sorry for the carelessness on my side!!!
The method must be static...
lakshmi nair
I agree. Here's the link:
subject: singleton class
jQuery in Action, 3rd edition