【问题标题】:Cannot override generic interface无法覆盖通用接口
【发布时间】:2014-06-19 18:25:54
【问题描述】:

我正在尝试创建泛型类型方法的接口,然后在子类中实现它们等等。但是我不知道为什么我的子类会抛出一个错误,说我没有从我的接口覆盖抽象方法。代码如下:

package stdmathops1;
public interface StdMathOps1<T>{
    public <T> T div(T f, T s);
    }
//this is all very simple and not the whole of it, at this point I'm just
//trying to figure out why it won't override the div method.
class Fraction implements StdMathOps1{
    public static void main(String[] args){
    }
    public <T extends StdMathOps1> T div(T f, T s){
        return f;
    }
}

无论我在哪里寻找覆盖和使用接口,它似乎都是正确的,但它仍然会抛出

Fraction is not abstract and does not override abstract method div(Object, Object)
in StdMathOps1

任何帮助将不胜感激

【问题讨论】:

  • 您正在添加一个条件,更改您的方法,使其实际上不会被覆盖。接口中的方法指定了任何类类型 &lt;T&gt;,而您的覆盖尝试指定了必须扩展或属于 STDMathOps1 的类类型

标签: java generics interface overriding abstract-class


【解决方案1】:

您通常不能像在重写方法上那样更改参数的界限。对于编译器,

public <T> T div(T f, T s);

public <T extends StdMathOps1> T div(T f, T s);

是两种不同的方法。

欲了解更多信息,请参阅Cannot override generic interface

【讨论】:

  • 他们没有相同的擦除。
  • 你是对的。我的错误,忘记了有界类型上的擦除擦除到有界类型。
猜你喜欢
  • 2021-03-26
  • 2013-11-14
  • 2014-10-23
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
相关资源
最近更新 更多