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 nested loop? What is dangling else condition in it?

814


In how many ways we can do exception handling in java?

786


What is a java lambda expression?

789


What is a method in java?

724


How will you load a specific locale?

738


What is the equal sign?

805


What do you mean by aggregation?

820


What are the types of relation?

796


What is the difference between checked exception and unchecked exception?

778


List some features of the abstract class.

787


What is class forname?

733


What is command line used for?

825


What is difference between next () and nextline () in java?

760


What are the advantages of autoboxing?

754


What steps are taken when the OS shifts from one-thread execution to another?

1126