This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
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

Win a copy of Elasticsearch in Action this week in the Big Data forum!
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

how to make single instance of a class?

Kartik Mahadevan
Ranch Hand

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

BalajiS Sridharan

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


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
I agree. Here's the link:
subject: how to make single instance of a class?