This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Static object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Static object" Watch "Static object" New topic

Static object

Dev Cunningham

Joined: Oct 12, 2001
Posts: 9
What's the best way to create an instance of a Java class that 'globally' available throughout my application? For instance, with C++ I might create an object when my application starts and store a pointer to that object in a global variable.
In this case, I am creating a hash table, which is useful to many parts of my application. Obviously I don't want to create the hash table each time I need to use it.
Greg Brouelette
Ranch Hand

Joined: Jan 23, 2002
Posts: 144
Do a quick search for "Singleton" on this board.
A "Singleton" object is an object designed in such a way that you can't actually make a new instance of it. You use a static getInstance() method instead. If this is the first time that the getInstance method was called then the object is constructed. On the 2nd and subsequent time that it's called then the method returns the already constructed object.
Here's an example:

[ May 15, 2002: Message edited by: Greg Brouelette ]

For a good Prime, call:<br />29819592777931214269172453467810429868925511217482600306406141434158089
Dev Cunningham

Joined: Oct 12, 2001
Posts: 9
Thanks Greg!!
That looks perfect.
It is sorta covered in the JavaRanch Style Guide.
subject: Static object
Similar Threads
How to insert password in an encrypted form into a table
hashCode/equals stratgy for mutable object
Doubt in Hash Map and Hash Table
Hash Table (dunno if I should post it here though)
Hash table