0


I have a singleton class, call Class A, then I have another class, called Class B, and Class B extends from class A. What I want is that, after instance of class A is created, when the instance of class B is created after that, it will have the same information as class A have. Is it possible in Java ?
Thank you very much.
P/S: This is how I created a singleton class

public static A getInstance() {
    if (instance == null) {
        instance = new A();
    }
    return instance;
}
Xitrum
  • 7,765
  • 26
  • 90
  • 126
  • Depends, how are you making sure it's a singleton? – EpicPandaForce Mar 12 '15 at 11:38
  • You probably just need to make a Constructor for B that takes the instance of `A` as a parameter, and then copy itself into B. – EpicPandaForce Mar 12 '15 at 11:38
  • The *design* path you are taking will give you *sleepless nights*. beware my friend.. There are workarounds to do this, but definitely not advisable. Singleton almost always is used in a *has-a* relationship (if at all) – TheLostMind Mar 12 '15 at 11:38
  • 4
    It doesn't look like singleton since singletons have private constructor which prevents it from being extended (unless `B` is inner class of `A`) – Pshemo Mar 12 '15 at 11:38
  • 1
    @Pshemo wait, you can't extend from a class with a private constructor? I didn't know that. Cool. – EpicPandaForce Mar 12 '15 at 11:39
  • 1
    @EpicPandaForce You need to be able to invoke `super()` in extending class constructor, but if this `super` is private then it is impossible to invoke it, which makes our `extend` pointless. – Pshemo Mar 12 '15 at 11:40
  • 2
    If you have a singleton `A` and `B extends A` and you somehow allow this through a `protected` constructor in `A` then you effectively have two instances of `A`. That is not the _singleton_ pattern at all. – Oli Mar 12 '15 at 11:41
  • 1
    @EpicPandaForce Technically, you can extend from a class with a private constructor in the same compilation unit (meaning that nested or private classes can extend). – chrylis -cautiouslyoptimistic- Mar 12 '15 at 11:45
  • @chrylis - Or by adding another constructor which isn't private :P – TheLostMind Mar 12 '15 at 11:46
  • 2
    @EpicPandaForce if you want to prevent class from being extend, define it as `final` – user902383 Mar 12 '15 at 11:47
  • @user902383 Aye, I knew about that :) although nowadays if I need a singleton, I just use the `enum singleton pattern` like so http://stackoverflow.com/a/27040452/2413303 – EpicPandaForce Mar 12 '15 at 11:49
  • 2
    @EpicPandaForce yes, i'm using enum for single tons as well, at least since i read effective java – user902383 Mar 12 '15 at 12:00

1 Answers1

2

You can inherit from a singleton class A by making A's constructor protected instead of private.

But if you're inheriting from singletons, you should probably take another look at your design.

Siqi Lin
  • 1,237
  • 1
  • 10
  • 25