In the following java code, NetBeans complains with or without the @Override statement.
If the Override is not present I get an error that the return types Pair<Interval, Interval> and Pair<ExtendedInterval, ExtendedInterval> are not compatible. The interpreter suggests that I add an @Override statement. However, the same error occurs with the @Override statement.
What’s the best way to make this error go away? I would prefer that the caller not have to cast the returned objects to the correct class.
public class Interval {
private Date left;
private Date right;
public Pair<Interval, Interval> split(Date dt){
...
return new Pair<Interval, Interval>(
new Interval(left, dt),
new Interval(dt, right));
}
}
public class ExtendedInterval extends Interval {
private Data localData;
@Override
public Pair<ExtendedInterval, ExtendedInterval> split(Date dt){
Pair<Interval, Interval> baseInterval = super.split(dt);
return new Pair<ExtendedInterval, ExtendedInterval>(
new ExtendedInterval(localData, baseInterval.first()),
new ExtendedInterval(localData, baseInterval.second()));
}
}
Well, you could change the base class method to:
I believe that would work.
The problem is that without that, it simply isn’t type safe. Suppose
Pairhas asetFirst()method to set the first part of the pair. Then you could have:That looks fine from the compiler’s point of view, but it’s unlikely that you should be able to call
setFirst(Interval)on aPair<ExtendedInterval, ExtendedInterval>.Now all of this applied even if there isn’t actually a
setFirstmethod – because you can’t tell the Java compiler that thePair<>type itself is covariant; the generic variance is done at the use of the type.