hello
I want to know to how to make class singleton but donot make constructor private and method static.
means want to something which is not possible to clone. Something like that
Thanks
Regards
Rahul

and ... why not make the constructor private? if the constructor is not private, what's to stop us from creating multiple instances?

Comments
spot on!

somjit: IMHO the second example isn't a good one, since that Singleton won't be a Singleton.
1. every single class within that same package can create an unlimited amount of instances of that class.
2. every child class can create an unlimited number of instances of that class
3. through instantiating the child class (since the parents constructor is called) basically ever class can.

i do agree.
gave that link because it was the simplest one (to read an understand) amongst the few that turned up with a quick google. my bad that i didnt explain the protected access modifier's effect/limitations in that second example. however, you did it in a more short-n-sweet way than i could have. thanks :)

Edited 3 Years Ago by somjit{}

A lot depends on how robust you want he to be. A simple public static getInstance with a private constructor that's called from a static initialiser block is good enough for some situations, but there are all kinds of problems in a multi-threaded situation, or if you have multiple class loaders or if you use serialisation.
This discussion covers the options pretty well, but in short, since java 1.5, the preferred solution is to have an enum with a single value

Sir
Actually it asked by someone and he suggested me not to use combination private constructor and static method to do that.
thats why i mention it.Also we asked did i do the same thing so that i can't make a copy of that
thanks
regards
rahul

an alternative to the classic way to create singletons that some people promote is to create an enum with a single instance.

public enum Something {
  INSTANCE;

  public void doSomething() {
        System.out.println("something");
  }
}

bit contrived IMO, but it works.

A bit contrived maybe, but it's promoted as the preferred solution because it's guaranteed thread-safe, and immune to duplication of the "singleton" via multiple class loaders or serialisation/deserialisation. Protecting against all those in the traditional versions becomes really tedious.
If you're not worried about obscure corner cases then the private constructor / initialise in a static initialiser block / access via static getter (or use public final) is just fine.

Edited 3 Years Ago by JamesCherrill

This article has been dead for over six months. Start a new discussion instead.