0

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?

1
  • I don't think so. Commented Feb 11, 2021 at 4:06

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.