I am defining the following class:
public class Foo<T> {
T _value;
public T getValue() {
return T;
public void setValue(T value) {
_value = value;
}
}
T should only be of type int, char, or double.
I want to be able to reference a collection of these, such as:
interface IBar {
Collection<Foo> getAllFoo();
}
Obviously, this doesn’t work since I’d need to specify the type T with this reference. So, I need to define some abstract base class that I can use instead.
The question is, how can I enforce that all derived types implement the getValue() and setValue() functions? I know I can define them in the abstract base as abstract methods returning / accepting an Object, but that doesn’t provide type safety on the 3 accepted primitives.
Is there a better way to define a collection of these, and is there a way to enforce T being either int, char, or double?
You’re better off creating concrete implementations for each type you care about.
The
?allows the collection to contain any type ofFooobject. You still lose the generic type when you reference aFoo<?>, but there’s no good way around that.Other than having the common base class, there really is no advantage of doing this. If you had some common ground each
Foocould resolve to, then I would do this: