Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend a Singleton class

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;
 }
}
like image 983
Bosco Avatar asked Jun 26 '26 04:06

Bosco


1 Answers

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

like image 134
CupawnTae Avatar answered Jun 27 '26 18:06

CupawnTae



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!