How to implement Singleton

Answer Posted / shaik baji

Singleton Example:
==================
public class Singleton
{
private static Singleton singleton;

private Singleton()
{
}

public static Singleton getInstance()
{
if(singleton==null)
{
singleton = new Singleton();
return singleton;

}
else
{
return singleton;
}

}

}


Accessing Singleton instance
============================
public class STDemo
{
public static void main(String[] args)
{
Singleton obj1= Singleton.getInstance();
System.out.println(obj1.hashCode());

Singleton obj2= Singleton.getInstance();
System.out.println(obj2.hashCode());

Singleton obj3= Singleton.getInstance();
System.out.println(obj3.hashCode());

}
}

Is This Answer Correct ?    0 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is native method in java?

561


What is outofmemoryerror in java?

560


What is final modifier?

556


What happens if we don’t define serial version uid?

566


What are three advantages of using functions?

532






What type of variable is gender?

540


What is a container in a gui?

545


Explain different ways of creating a thread?

527


Can we have any code between try and finally blocks?

556


What are streams?

629


How do you know if a value is nan?

562


Explain about the select method with an example?

587


What is the flag in java?

608


What does this () mean in java?

543


Is java 1.7 the same as java 7?

530