How to implement or use the singleton class in java?

Answer Posted / pinaki mukherjee

A singleton is an object that cannot be instantiated. At
first, that might seem counterintuitive - after all, we need
an instance of an object before we can use it. Well yes a
singleton can be created, but it can't be instantiated by
developers - meaning that the singleton class has control
over how it is created. The restriction on the singleton is
that there can be only one instance of a singleton created
by the Java Virtual Machine (JVM) - by prevent direct
instantiation we can ensure that developers don't create a
second copy.

We'll start with the class definition, for a SingletonObject
class. Next, we provide a default constructor that is marked
as private. No actual code needs to be written, but you're
free to add some initialization code if you'd like.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
}

So far so good. But unless we add some further code,
there'll be absolutely no way to use the class. We want to
prevent direct instantiation, but we still need to allow a
way to get a reference to an instance of the singleton object.

Is This Answer Correct ?    3 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are the differences between the java collection and the java list? : java collections

621


What are the different types of classes implemented in the set interfaces? : java collections

619


What is the use of hashcode in java ?

583


What is the difference between comparable and comparator in java.util pkg?

604


what is mean by hasing and maping in java platform and advantage?

1841






How do I find jre path in windows?

535


Which java collection class can be used to maintain the entries in the order in which they were last accessed?

568


can u draw class/object diagram for ATM

5541


What is an algorithm in java collection framework? : java collections

589


Hi frnds how to lock an user when he enter wrong credentials more than 3 time using java or j2ee tech take username and password in a bean no need to connect DB and validate give me some sample application code or links its urgent for me thanks in advance

1884


my interviewer asked me what technical specification you used how to answer that question

1943


What are the uses of the set interfaces in the java collections? : java collections

544


What are the queues in the java collection framework? : java collections

557


What are the types of interface used in the java collections? : java collections

591


What is iterator in the java collections framework? : java collections

543