3

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;
 }
}
Bosco
  • 3,835
  • 6
  • 25
  • 33
  • java? what is prog lang – Abdennour TOUMI May 10 '14 at 06:46
  • In addition to @AbdennourToumi's comment, please post the code to your Demo() class and the original singleton you're trying to extend to help us troubleshoot. Seems like you have a private constructor in the original singleton class. – Gary Schreiner May 10 '14 at 06:48
  • Error message indicates java, but I agree with the above comments - you should add more detail to the question, and tag it with java if that's correct – CupawnTae May 10 '14 at 06:55
  • I thought, behavior of Singleton class is not language specific, so I didn't add tag for java – Bosco May 10 '14 at 07:43
  • possible duplicate of [What is an efficient way to implement a singleton pattern in Java?](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java) – fredoverflow May 10 '14 at 08:10
  • possible duplicate of [How to resolve 'Implicit super constructor classA() is not visible. Must explicitly invoke another constructor'?](http://stackoverflow.com/questions/3904355/how-to-resolve-implicit-super-constructor-classa-is-not-visible-must-explici) – Raedwald May 10 '14 at 11:30

1 Answers1

8

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

CupawnTae
  • 14,192
  • 3
  • 29
  • 60