*
The moose likes Beginning Java and the fly likes How do I force class to be a static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do I force class to be a static" Watch "How do I force class to be a static" New topic
Author

How do I force class to be a static

Siva kandasamy
Ranch Hand

Joined: Dec 31, 2002
Posts: 139
Hi There,
How do I force class to be a static.
Meaning I want to create only one instance of that class.
Thanks in advance
siva
Stephen Pride
Ranch Hand

Joined: Sep 14, 2000
Posts: 121
You may want to use a Singleton class (if I understand you correctly).
For example ...

This will guarantee only one instance of the class. Note the private constructor and private/static object.


SCJP
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2839
    
  11

It's a good idea to synchronize the getInstance() method of a singleton, just on the off chance that two threads try to simultaneously call it for the first time. Without the synchronization, there is a slight chance that you could get two instances.
Siva kandasamy
Ranch Hand

Joined: Dec 31, 2002
Posts: 139
Thanks. I am new user this forum and
finding very usful. Thanks to all the great folks here.
thanks
siva
x38020
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
See http://c2.com/cgi/wiki?SingletonPattern for a discussion on the subject. Specifically, be very carefull about overusing this pattern...


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How do I force class to be a static
 
Similar Threads
Iterations - finding the same value for 2 variables
ClassLoader .getSystemResourceAsStream()
Stop creating object
Axis Parser Error
Parsing Problem