nancy andrew wrote:I was recently asked this question: Create a singleton class which returns same object of that class itself everytime.
I know singleton class looks like this:
But i should not use a new operator like instance = new TestSingleton(); In short, my program should return same instance of same class everytime. Any pointers??
You have to use the new operator once to create the single instance that you are going to return every time for all future calls to getInstance.
Your code is generally correct although it could have problems in a multithreaded environment. You need to either make your getInstance method synchronized or initialise the instance variable at the same time as you declare it.
Search these forums for examples of how it should be done.