简体   繁体   中英

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.

How do I define method in interface to make method public String talk(Result<String> result) override method of interface?

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 since everything extends object, you are not liming anything with that expression

? represents a wild-card but not a generic. Try the following.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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