Singleton Design Pattern and its child class's default constructor - java

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 SubClass then it automatically invokes the constructor of its SuperClass to initialize its fields, and that further invokes all the superclass constructors in the inheritance hierarchy
Now since your SuperClass constructor is private, so it cannot invoke that. So, you are getting that exception..
But it doesn't make sense to subclass a singleton class, because in that case, your class will no longer be singleton.
You should re-think about your design and what you are trying to do. And change your design accordingly.

SingleTon class are not supposed to be inherited so below ensures that
private Singleton() {
Below code
public SubClass(){
System.out.println("I am sub class");
}
Is same as :
public SubClass(){
super(); //Error here as super class constructor is private
System.out.println("I am sub class");
}

Because your Singleton class no-arg constructor is private. When you instantiate sub-class it tries to instantiate super class also. But your super class has private constructor. It fails.
private Singleton() {
System.out.println("I am user class");
}
It doesn't make sense to subclass Singleton class. You may need to re-think about your design.

First of all, subclassing a singleton class is breaking the basics of Singleton Pattern.
Secondly, due to the chain of calling the constructors through the inheritance tree, you get that exception since the constructor of the parent class is private.
You will probably add a public constructor with some parameters to make the child inherit from its parent. Then you will have maybe many instances of SubClass. Any Subclass instance IS-A Singleton instance, too. And this is against the purposes of Singleton pattern. That's why you should avoid subclassing a singleton class.

Related

Singleton contract using inheritance?

I'm trying to create a framework where Singleton objects can get the core of their implementation from. The use for this is so if I make multiple Singleton classes, I don't need to re-write their (while simple) implementations over and over.
I tried this:
public abstract class Singleton
{
protected static final Lock mutex = new ReentrantLock(true);
// Not even subclasses are allowed to mess with `instance`.
private static Singleton instance = null;
// Here is the problem, static methods cannot be abstract.
protected static abstract Singleton init();
public static Singleton get()
{
mutex.lock();
// The super class has no idea how to instantiate
// this singleton, so let subclasses handle that
// via the abstract init method
if (instance == null)
instance = init();
mutex.unlock();
return instance;
}
}
But it really cannot work because the whole concept of static members with inheritance doesn't go well together.
My other option is to do:
public enum Singleton
{
INSTANCE
}
But since enum cannot be extended, I cannot do:
public enum MySingleton extends Singleton
{
// Member variables and functions here
...
}
I could have every implementation just be an enum and the only code I have to repeat (I think?) is INSTANCE unless I'm missing something? The only downside I see there is the Singleton is created at the beginning of the runtime and not on-demand later on in the program.
I could also do an interface but then I get stuck here:
public interface Singleton
{
Singleton instance = null;
default void set(Singleton s)
{
assert instance == null;
assert s != null;
// cannot do this, as `instance` is FINAL
instance = s;
}
}
What's the best way to do define a Singleton contract without having to retype the entire implementation over again?
Thanks

Singleton + Abstract class issue

I'm trying to define this inheritance:
public abstract class GameAction extends Observable {
protected static GameAction instance = null;
protected GameAction() {
// Exists only to defeat instantiation.
}
//All GameActions are singletons
public static abstract GameAction getInstance();
}
public class ChooseAnswerAction extends GameAction {
protected ChooseAnswerAction() {
// Exists only to defeat instantiation.
}
//All GameActions are singletons
#Override
public static GameAction getInstance() {
if(instance == null) {
instance = new ChooseAnswerAction();
}
return instance;
}
}
The problem is that the getInstance() method in the second class doesn't find the same one on his father, therefor it asks me to remove the #Override.
Also on the parent class I get the following error:
The abstract method getInstance in type GameAction can only set a visibility modifier, one of public or protected
The only way I could fix this error was taking out the static modifier, but I need it...
Thank's for your time!
Here is my go to link on singleton. Since Aleksey Shipilёv has made a very detailed post - I am linking you there.
http://shipilev.net/blog/2014/safe-public-construction/
In your case, since you are returning the child singleton instance, I would recommend that the instance object be in the child class. Also, you may want a better design and think about using a singleton factory.
The short answer is, that you can't override static methods since they are bound to the superclass.
The long answer is, that this makes implementing singleton inheritances complicated (assuming you want to hold the instance in the superclass). See singleton and inheritance in Java

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;
}
}
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

Regarding changing the constructor specifier from private to protected of singleton

What would happen if we change the constructor of the singleton from private to protected? How we can prevent it breaking in that case?
Singleton:
public class SingletonObject
{
private static SingletonObject ref;
private SingletonObject () //private constructor
{
System.setSecurityManager(new SecurityManager());
}
public static synchronized SingletonObject getSingletonObject()
{
if (ref == null)
ref = new SingletonObject();
return ref;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException ();
}
}
For breaking the singleton the following url contains the required info cracking singleton with other ways.
From Joshua Bloch's Effective Java on Singletons Properties:
The private constructor is called only once, to initialize the public
static final field (...). The lack of public or protected
constructors guarantees a “monoinstance” universe: Exactly one (...)
instance will exist once the Singleton class is initialized—no more, no
less. Nothing that a client does can change this.
So, if you make your Singleton Constructor protected you're exposing your Constructor to let any class in the same package to make instances an instance of SingletonObject. If that happens, your Singleton Pattern is broken.
Relaxing the access modifiers of the constructor on any way -making it protected, public or default- is an open gate to instance generation, and that's not desired in a Singleton implementation.
Simple: Changing the constructor access modifier from private to protected allows any class in the same package to instantiate SingletonObject. We can easily create a class "in the same package" by specifying the corresponding package statement.
Edit: The answer of Carlos made me realize an additional problem that results from making the constructor protected as opposed to public: A subclass of the singleton class can be created (in another package), which can be freely instantiated and have its instance methods called; the singleton class itself no longer has full control over where and how instances (or 1 instance) are created.

When and Why would a Child class declare a static instance member of the parent class?

This is another design pattern in some legacy code that I couldn't find much about on google. In this case a child class extends its abstract parent, but then turns right around and declares a static instance of the parent:
public abstract class MessageBase {
protected DAOFactory factory;
// method declarations
}
public class EDWMessage extends MessageBase {
private static MessageBase instance;
public static MessageBase getInstance(Properties properties) {
if (instance == null) {
instance = new EDWMessageTransaction(properties, null);
}
return instance;
}
//more code
}
I'm not sure I understand what would drive this design pattern (if it is a known pattern). Is this a sort of convenience pattern to avoid declaring each member variable of the parent as static? Or is it meant to allow multiple children classes to each have one instance of the parent. But if that's the case, why the excessive use of inheritance over just plain composition?
The rest of the code gives no indication as to why it would be done this way. Any thoughts or ideas would be much appreciated. Thanks!
P.S. I seem to be running in to a lot of interesting design patterns in this legacy code that I don't know how to handle. Thanks to everyone who has helped me out already.
Edit: Expanding the code sample. Will edit again as I discover someplace that actually uses this code. Yay for no documentation.
This is a common idiom for thread-safe lazy singleton initialization. If you can have a singleton class, you delegate to a private static instantiating class.
public class MySingleton{
private MySingleton(){
}
public static MySingleton getInstance(){
return SingletonCreator.INSTANCE;
}
private static class SingletonCreator{
private static final MySingleton INSTNACE = new MySingleton();
}
}
Not sure if this is how your child class is being used, but this would be a use case for a child class holding a static instance of its parent
The original intent probably was that for each subclass of MessageBase there should only be 1 instance and that you can access that instance with a commom method in the base class
so you could iterate over all message types and get the instance of each
my 2cents

Categories

Resources