user3236409
user3236409

Reputation: 41

Method in abstract class returning an instance of the class that implements it

Is it possible in an abstract class to have a method that 'generically' returns an instance of the class that extends it?

Upvotes: 1

Views: 575

Answers (2)

Kayaman
Kayaman

Reputation: 73528

You could instantiate the class in the following way, but maybe you should tell us what you're trying to achieve. Another simpler way would probably be to implement Clonable.

public abstract class AbstractClass {
    public AbstractClass getInstance() {
        return getClass().newInstance();
    }
}

or in the case of a constructor accepting parameters:

return getClass().getDeclaredConstructors(String.class, Integer.class).newInstance(someString someInteger);

Upvotes: 3

Paul Richter
Paul Richter

Reputation: 11072

This is just to provide a bit of extra information, and to answer your question in the comments. Kayaman's answer is exactly what I would have suggested as well, given the information in your question.

However, as you implied with your comment-question, this method will only invoke the default constructor. In order to invoke one of the parameterized constructors, you need to effectively "locate" it by its signature using the getDeclaredConstructor method.

Like so (borrowing from Kayaman's answer):

public abstract class AbstractClass {
    public AbstractClass getInstance(Object[] parameters, Class<?>...parameterTypes) {
        return getClass().getDeclaredConstructor(parameterTypes).newInstance(parameters);
    }
}

Making sure of course that the order of elements in parameters and parameterTypes corresponds to the constructor's signature.

Upvotes: 1

Related Questions