Reputation: 1432
I have a class that is maintaining a list of objects of type Baz. However, I want to put some objects in this list that are instantiated from subclasses of type Baz (for overridden behavior).
So far, this is simple enough -- polymorphism in a List. However, the class maintaining the list is itself abstract, and different implementations will require that different types be placed in the list. Some abstract function getTypeToUse should specify the type of the element to insert into the list. Is this possible in Java?
Consider the following pseudocode:
public abstract class Foo {
public void Bar() {
List<Baz> qux = new ArrayList<>();
Type buzz = getTypeToUse();
Baz fizz = new buzz();
qux.add(fizz);
}
// The returned Type should be some subclass of Baz
// It would be nice to enforce this, like <? extends Baz>
public abstract Type getTypeToUse();
}
Thank you!
Upvotes: 1
Views: 46
Reputation: 28066
You could return a class object instead. The class Class<T>
implements the interface Type
. Define your method like this:
public abstract Class<? extends Baz> getClassToUse();
Then implement it like this (in class Baz):
@Override
public Class<? extends Baz> getClassToUse() {
return Baz.class;
}
Upvotes: 2