• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can singleton classes be subclassed?  RSS feed

 
Collin Dugas
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI All,

I was asked if a singleton class can be subclassed in any way?

This was my answer.

Yes.

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.

But it can be sub classed in the same class. Another method can create an anonymous subclass and return it or use it for its internal purpose. It will not serve any practical

purpose but it can be done.

I tried it in a sample program and it worked.


Would like to know your opinion on it.

Thanks
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends whether or not your Singleton is declared final. That is the normal mechanism to prevent a class being extended. Remember, "singleton" is a pattern which could be implemented in different ways.
 
Ulrika Tingle
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Collin Dugas wrote:
I was asked if a singleton class can be subclassed in any way?


The Singleton design pattern is defined in Design Patterns by Gamma (and others).

Under Consequences it's stated that a Singleton "3. Permits refinement of operations and representation" and that this includes subclassing.

Also under Consequences is another interesting fact. A Singleton "4. Permits a variable number of instances". So not even this commonly held notion that a Singleton must have exactly one object instance is cut in stone. The Singleton definition allows it to vary.

What you can ask of course is whether a certain Singleton implementation has some specific limitations in relation to the Singleton definition.
 
Collin Dugas
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Sturrock wrote:It depends whether or not your Singleton is declared final. That is the normal mechanism to prevent a class being extended. Remember, "singleton" is a pattern which could be implemented in different ways.


Okay, I get it now. Maybe, the interviewer wanted to know how or if you could subclass a class with private constructor.

Thanks, I will think of Singleton from a pattern perspective rather than a class perspective.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!