-1

I am actually trying to implement something where a singleton class would extend a non-singleton class.

I've tried reading multiple answers but none of them answer my question.

class Parent{
    // Code goes here
}

class MySingleton extends Parent{
    // Code goes here
}

I have 2 questions now.

1) Is this possible in java/kotlin?

2) If yes, is it a good practice? Please provide some reference.

1 Answers1

2

1) Is this possible in java?

Yes, but.

It depends how you implement your singleton. Singleton has become more of an anti-pattern over the years, and when you still use it, then it is good practice to use enums:

public enum SomeSingleton { 
  INSTANCE;
  ...

which of course: doesn't work when you want to extend a parent class.

2) If yes, is it a good practice? Please provide some reference.

As said, singleton alone is (mostly) regarded bad practice these days. So adding another constraint sure doesn't make things better.

Conceptually, it sounds wrong. What if someone does this:

List<Parent> someInstances = Arrays.asList(parentInstanceA, parentInstanceB, thatSingletonInstanceOfMySingleton);

All of a sudden, you have multiple things that of course aren't exactly the same, but well, they all go into that list nicely.

Long story short: I wouldn't do it. If at all, use an enum, and then consider to use composition instead of inheritance.

GhostCat
  • 137,827
  • 25
  • 176
  • 248