I ran into a problem when trying to specialize a class that implements a generic interface where I wanted to inherit from the same interface as the super class, but with a more specific type argument. The following snippet shows a synthetic but complete example that cannot be compiled. The comment contains the error message from the Java compiler.
interface Producer<T> {
T get();
}
class NumberProducer implements Producer<Number> {
@Override
public Number get() { return null; }
}
// Producer cannot be inherited with different arguments: <java.lang.Integer> and <java.lang.Number>
class IntegerProducer extends NumberProducer implements Producer<Integer> {
@Override
public Integer get() { return null; }
}
In the PECS sense, Producer<T>
is a producer, so Producer<Integer>
would be a subtype of Producer<Number>
, but there's no way to declare that in the definition of Producer<T>
. Java does not allow IntegerProducer
to inherit from NumberProducer
and Producer<Integer>
at the same time as IntegerProducer
would then inherit from Producer<Integer>
and Producer<Number>
at the same time.
Is there a standard approach to this limitation, e.g. a pattern that solves the same problem without requiring this kind of inheritance?