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

525


What is the meaning of nullable?

580


What is meant by flickering?

658


What is a nested class?

598


Which programming language is best in future?

529






Why string is not thread safe?

545


What are the different data types in java?

536


What is difference between this and super keyword?

524


What will happen to the exception object after exception handling?

582


What is the use of put method?

524


What is meant by JVM? Is JVM platform independent or not?

581


How do you declare an array in java?

524


What does @override mean?

538


What is boolean law?

522


How to create a thread in java?

608