In my coding, I use Singleton class with Singleton Design Pattern. Question is why its sub class does not allowed to use default constructor?
I get compile time error :
Implicit super constructor Singleton() is not visible. Must explicitly invoke another constructor
Singleton.java
public class Singleton {
private static Singleton singleton;
private Singleton() {
System.out.println("I am user class");
}
public static Singleton getInstance() {
if(singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
SubClass.java
public class SubClass extends Singleton {
public SubClass(){
System.out.println("I am sub class");
}
}
When you create an instance of
SubClassthen it automatically invokes theconstructorof itsSuperClassto initialize its fields, and that further invokes all the superclass constructors in theinheritance hierarchyNow since your
SuperClassconstructor is private, so it cannot invoke that. So, you are getting that exception..But it doesn’t make sense to
subclassasingletonclass, because in that case,your class will no longer be singleton.You should
re-thinkabout yourdesignand what you are trying to do. Andchangeyour design accordingly.