Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Inherit and Be a Singleton

To begin with, I am NOT trying to create a subclass of a singleton class. (At least I'm sure I'm not trying to).

I have a class ClassA that is abstract.

I have two classes, ClassA1 and ClassA2 that extend ClassA.

I want ClassA1 and ClassA2 to be singleton classes. I could just write the code in each one to do so but I would prefer to write the code once in ClassA and reuse it in all of it's sub-classes. Is there a way to do this?

like image 241
Sababado Avatar asked Feb 20 '23 12:02

Sababado


2 Answers

Probably not - the singleton pattern requires static methods/fields, which would be shared by ClassA and all its subclasses if defined in one place.

like image 155
Rob I Avatar answered Mar 07 '23 20:03

Rob I


I would suggest private constructors for ClassA1 and A2 and having static methods for object creation. This way you have complete control over object creation. The book EffectiveJava details out the adavatages of this approach.

like image 42
Scorpion Avatar answered Mar 07 '23 19:03

Scorpion