Java - How to define the interface method with generic


I created interface:

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

And this implementation:

class A implements SubApp{
   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> {
    public String talk(Result<String> result) { ... }