File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Java class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java class" Watch "Java class" New topic

Java class

Anjali Ajwani

Joined: Jan 18, 2001
Posts: 16
How can I ensure that a class has only one instance?
Dale DeMott
Ranch Hand

Joined: Nov 02, 2000
Posts: 515
Create the class in a Singleton design pattern. See the "OO, Patterns, UML and Refactoring" group for more details. Basically you will be using a method called instance() to retrieve the instance. if the instance already exists, you will return it, else you will create a new one. There will be a static varaible in the class that will hold the reference to this instance. Initially it is null. Something like the following code.

Hope this helps
What's this H2SO4 doing in my fridge?? ( thud )
[This message has been edited by Dale DeMott (edited June 14, 2001).]

By failing to prepare, you are preparing to fail.<br />Benjamin Franklin (1706 - 1790)
Anjali Ajwani

Joined: Jan 18, 2001
Posts: 16
Thanks Dale. This is what I was looking for.
Wirianto Djunaidi
Ranch Hand

Joined: Mar 20, 2001
Posts: 210

Remember to make the instance() method synchronized, else
there might be a possibility you end up with more than 1 instance
of the object.
Another way is just make the instance() method return the _instance object, and during declare _instance with:

Most of the VM will do lazy instantiation of that object anyway.
rani bedi
Ranch Hand

Joined: Feb 06, 2001
Posts: 358
Can you please explain how will it restrict creation of more than one instance in a VM?
I tried to create 2 instances with this code and got successful.

Cheers,<br />Rani<br />SCJP, SCWCD, SCBCD

Joined: Jun 28, 2001
Posts: 5
You don't create 2 instance, you just declared i as static. In
this case it doesn't matter how many instance you'll create. Change i from static to non-static and you'll see same result which means we've created only one instance of the class.
Have a nice day.
I agree. Here's the link:
subject: Java class
It's not a secret anymore!