开发者

Java: Overriding Method in Derrived Class with Different Return Type?

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);
        ret开发者_开发技巧urn new Pair<ExtendedInterval, ExtendedInterval>(
                              new ExtendedInterval(localData, baseInterval.first()),
                              new ExtendedInterval(localData, baseInterval.second()));
    } 
}


Well, you could change the base class method to:

public Pair<? extends Interval, ? extends Interval> split(Date dt)

I believe that would work.

The problem is that without that, it simply isn't type safe. Suppose Pair has a setFirst() method to set the first part of the pair. Then you could have:

Interval x = new ExtendedInterval();
Pair<Interval, Interval> pair = x.split(new Date());
pair.setFirst(new Interval());

That looks fine from the compiler's point of view, but it's unlikely that you should be able to call setFirst(Interval) on a Pair<ExtendedInterval, ExtendedInterval>.

Now all of this applied even if there isn't actually a setFirst method - because you can't tell the Java compiler that the Pair<> type itself is covariant; the generic variance is done at the use of the type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜