aspose file tools*
The moose likes Beginning Java and the fly likes Doubt with a singleton class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt with a singleton class" Watch "Doubt with a singleton class" New topic
Author

Doubt with a singleton class

Ravi Kiran Va
Ranch Hand

Joined: Apr 18, 2009
Posts: 2234

Hi please let me know

Is it mantadatory to have a singleton class as a protected / private constructor ??


Save India From Corruption - Anna Hazare.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19672
    
  18

Ask yourself this question: what classes can call a non-private constructor, and therefore create objects of a class?


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ravi Kiran Va
Ranch Hand

Joined: Apr 18, 2009
Posts: 2234

Thanks Rob , i agree my question is itself is vague .

I go with
For a singleton class, the constructor is made private and
a private static instance variable of its type and a public static method to get access for instatiating the class.


, but sometimes i saw examples where the author keeps the constructor as protected.
so the reason i posted.

can anybody please tell me why this so .
Sunil Kumar
Ranch Hand

Joined: Apr 24, 2007
Posts: 76
I see no reason for a singleton class to have a protected constructor. The purpose of "singleton" is then defeated.


Sunil Kumar
http://goodtoknowit.blogspot.com/
Ravi Kiran Va
Ranch Hand

Joined: Apr 18, 2009
Posts: 2234

Thanks sunil . If thats the answer i have no confusion with singletons.
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Sometimes we don't necessarily make the constructor private for testing purposes. I hope you get my point.

Moreover, you might want to read on the exact thing you encountered. Here is the wikipedia entry for Singleton, you need to scroll down a bit till "The solution of Bill Pugh".
Ravi Kiran Va
Ranch Hand

Joined: Apr 18, 2009
Posts: 2234

thanks a lot
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19672
    
  18

Sunil Kumar wrote:I see no reason for a singleton class to have a protected constructor. The purpose of "singleton" is then defeated.

It's mostly done so the singleton class can be subclassed, but I agree that it's a bad idea. Any class in the same package, as well as all sub classes, can also create new instances.
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Singleton Vs JustCreateOne, a must read.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt with a singleton class