I have an abstract singleton class and I want it to have an instance
field that represents the singleton's instance. I tried doing this:
public abstract class AbstractClass {
private static AbstractClass instance;
public static AbstractClass getInstance() {
return instance == null ? this.getClass().newInstance() : instance;
}
}
I want this to function so that when I call it from a subclass of AbstractClass
it returns an instance of that subclass, not an instance of AbstractClass
, which is why I tried using this#getClass()
instead of just AbstractClass
. This of course gives me an error stating "Cannot use this in a static context". Is there a way I can generate a new instance of a subclass in a static method in its superclass?
this
can not be used inside a static
method because there is no explicit object to resolve for the this
reference.
In addition to this constraint, Parent
class does not know about the possible subclasses(unless sealed
) that can extend from it.
So, it can't create an explicit instance of a subclass.
Based on your problem, you may want to approach some form of Factory
pattern to manage object creation. (or other creational pattern)