• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt with a singleton class

 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi please let me know

Is it mantadatory to have a singleton class as a protected / private constructor ??
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ask yourself this question: what classes can call a non-private constructor, and therefore create objects of a class?
 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see no reason for a singleton class to have a protected constructor. The purpose of "singleton" is then defeated.
 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks sunil . If thats the answer i have no confusion with singletons.
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Singleton Vs JustCreateOne, a must read.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic