简体   繁体   English

Java-如何使用泛型定义接口方法

[英]Java - How to define interface method with generic

I created interface: 我创建了界面:

public interface SubApp {
           public String talk(Result<? extends Object> result);
}

And this implementation: 和这个实现:

class A implements SubApp{
   @Override
   public String talk(Result<String> result) {...}
}

My IDE gives following error: Method does not override method from its superclass. 我的IDE给出以下错误:方法未从其超类重写方法。

How do I define method in interface to make method public String talk(Result<String> result) override method of interface? 如何在接口中定义方法以使方法public String talk(Result<String> result)覆盖接口的方法?

The issue with your approach is that your implementation is more specific than the interface definition, and thus your method won't accept the breadth of input your interface will, and that's not allowed. 您的方法的问题在于您的实现比接口定义更具体,因此您的方法将无法接受接口将要输入的内容,因此是不允许的。 (You can refine output types to be more specific, because an output type can be downward cast to the less specific type, but only the opposite is true for inputs). (您可以将输出类型细化为更具体的类型,因为可以将输出类型向下转换为次特定类型,但是对于输入而言,情况恰恰相反)。

Something like this should work: 这样的事情应该起作用:

public interface SubApp<T extends Object> {
    public String talk(Result<T> result);
}

class A implements SubApp<String> {
    @Override
    public String talk(Result<String> result) { ... }
}

Try something like this - 试试这样的事情-

public interface SubApp<T> {
  public String talk(Result<T> result);
}

class A implements SubApp<String> {
  @Override
  public String talk(Result<String> result) {...}
}

Try something like 尝试类似

public interface SubApp<T> {
   public String talk(Result<T> result);
}

btw, you never need ? extends Object 顺便说一句,你永远不需要? extends Object ? extends Object since everything extends object, you are not liming anything with that expression ? extends Object因为一切都扩展了对象,所以您不使用该表达式限制任何内容

? represents a wild-card but not a generic. 代表通配符,但不代表通用。 Try the following. 请尝试以下方法。

public interface SubApp<X extends Object>
{
     public String talk(Result<X> result);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM