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 loop in java?

521


What is the difference between numeric and integer?

509


Which collections are thread safe in java?

471


Explain about interrupt() method of thread class ?

655


What is finally and finalize in java?

585






How many bits is a float?

533


Is singleton class immutable?

532


What is singletonlist in java?

501


Can private method static?

469


How to restrict a member of a class from inheriting by its sub classes?

791


What is method overloading in JAVA? Why is it not present in C ?

584


Why singleton class is used in java?

563


what are the methods in object?

629


Define an applet in java?

627


What is stringreader?

520