Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make other classes derive from a singleton class?

Tags:

java

singleton

I am sorry if this is a duplicate or too elementary, but how do I make a singleton class that can be subclassed?

like image 540
unj2 Avatar asked Oct 22 '09 04:10

unj2


People also ask

Can singleton class inherit another class?

Unlike static classes, Singleton classes can be inherited, can have base class, can be serialized and can implement interfaces.

Can we create subclass of singleton class?

Subclassing a Singleton class may be tricky, since a subclass object cannot be created unless the superclass object has not yet been created. You may want to extend the Singleton class to allow not just a single instance, but some small fixed maximum number of instances.

What is the best way to subclass singletons?

A singleton class has a private constructor which is not accessible to any other class inside the same package or outside. Hence it cannot be sub classed from any other class.


1 Answers

Steve Yegge has an amusing article about singletons that mentions subclassing in this quote:

Then there's the subclassing thing. It's almost impossible to subclass a Singleton, and if you manage it, then you shouldn't have been using a Singleton in the first place. You don't even want to go there. I've walked roads that I dare not recount. Just pretend you can't do it, and you'll save yourself amazing amounts of pain.

like image 124
Chris Farmer Avatar answered Sep 21 '22 10:09

Chris Farmer