File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes how to make single instance of a class? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to make single instance of a class?" Watch "how to make single instance of a class?" New topic
Author

how to make single instance of a class?

Kartik Mahadevan
Ranch Hand

Joined: Feb 16, 2005
Posts: 47
Hi
I have to make a class which can be created only once .How do I do it ?

Regards
M.Kartik
BalajiS Sridharan
Greenhorn

Joined: Aug 29, 2005
Posts: 2
make the constructor private and have a public static method which will instantiate a instance but before instantiating check whether the variable is null or not

e.g.

public class SingleInstance
{
private SingleInstance()
{


}

private singleInstance;


public static SingleInstance returnSingleInstance()
{
if(singleInstance == null)
{
singleInstance = new SingleInstance();
}
return singleInstance;

}
}
[ September 05, 2005: Message edited by: BalajiS Sridharan ]
David Ulicny
Ranch Hand

Joined: Aug 04, 2004
Posts: 724
Just implement Singleton design pattern.


SCJP<br />SCWCD <br />ICSD(286)<br />MCP 70-216
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: how to make single instance of a class?
 
Similar Threads
How to load only one object in memory?
Make executable
Making a class executable.
Constructors and colours
how to make an exe for .class files ?