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

748


What is the difference between super class & sub class?

823


What do you mean by inner class in java? Explain

829


What is java literals?

798


What is the platform?

768


What is ph and buffers?

752


What is the name of the java compiler?

803


What is byte code and why is it important to java’s use for internet programming?

841


does java support pointers?

771


Write a program to print the pattern given below

736


Explain jvm, jre, and jdk?

806


how to deploy tomcatserver to weblogic server? write d following steps?

1708


What is the use of toarray () in java?

807


What is mysql driver class name?

835


How to create a custom exception?

766