Today I faced one question in interview. Is it possible to apply inheritance concept on Singleton Classes? I said since the constructor is private, we cannot extend that Singlet
Yes, it is technically possible, as singleton is a design pattern and not a language construct that could have inheritance restrictions. I would just reimplement the public [Object] getInstance()
method in the child classes (see below).
And, yes, singletons can also benefit from inheritance as they may share similar but not identifical behaviours with other singletons.
public class ParentSingleton {
private static ParentSingleton instance;
protected ParentSingleton() {
}
public static synchronized ParentSingleton getInstance() {
if (instance == null) {
instance = new ParentSingleton();
}
return instance;
}
public int a() {
// (..)
}
}
public class ChildSingleton extends ParentSingleton {
private static ChildSingleton instance;
public static synchronized ParentSingleton getInstance() {
if (instance == null) {
instance = new ChildSingleton();
}
return instance;
}
}
EDIT: as Eyal pointed out in his comments below, the constructor in the super class had to be made protected (instead of private), otherwise it would not be visible to the child classes and the code would not even compile.