Question

How do I extend a Singleton class? I get error : Implicit super constructor Demo() is not visible. Must explicitly invoke another constructor.

package demo;

public class Demo {

 private static Demo instance;

 private Demo(){}

 public static Demo getInstance(){
    if(instance ==null){
        instance=new Demo();
    }
    return instance;
 }
}
Was it helpful?

Solution

It's not strictly about it being a singleton, but by default when you extend a class, Java will invoke the parent's no-arg constructor when constructing the subclass. Often to stop people creating random instances of the singleton class, the singleton's no-arg constructor will be made private, e.g.

private Demo() {...}

If your Demo class doesn't have a no-arg constructor that's visible to the subclass, you need to tell Java which superclass constructor to call. E.g. if you have

protected Demo(String param) {...}

then you might do

protected SubDemo() {
    super("something");
...
}

and/or

SubDemo(String param) {...}
{
    super(param);
}

Note that if your Demo class has no non-private constructors, you won't be able to usefully extend it, and (if possible) you would need to change the protection level on at least one constructor in the Demo class to something that is accessible to your subclass, e.g. protected

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top