简体   繁体   中英

Implement generic interface with generic type in Java

I am trying to implement a generic interface in Java with a generic type and am getting compilation errors. I am wondering if the following is possible:

public class ListResponse<T> {
    private List<T> response;

    public ListResponse(List<T> response) {
        this.response = response;
    }

    public List<T> getResponse() {
        return response;
    }
}

And the troublesome class:

import java.util.function.Consumer;
import java.util.List;
import com.myorg.response.ListResponse;

public class ListPresenter<T> implements Consumer<ListResponse<T>> {
    private ListResponse<T> response;

    public <T> void accept(ListResponse<T> response) {
        this.response = response;
    }

    // Rest of class
}

I was hoping to then have calling code like this:

ListPresenter<Integer> presenter = new ListPresenter<>();

However I get a compilation error with the following message:

 error: ListPresenter is not abstract and does not override abstract
 method accept(ListResponse<T>) in Consumer [ERROR] where T is a
 type-variable: [ERROR] T extends Object declared in class
 ListPresenter

You are re-defining the generic parameter <T> on method accept(...) . The mechanic is similar to hiding attributes through local variables with the same name.

The T on public <T> void accept(ListResponse<T> response) is not "coupled" to the T on public class ListPresenter<T> implements Consumer<ListResponse<T>> .

The issue can be fixed by removing the first <T> on the declaration of method accept(...) :

public class ListPresenter<T> implements Consumer<ListResponse<T>> {
    ...
    public void accept(ListResponse<T> response) {
        ...
    }
    ...
}

In ListPresenter Class you are Not Implementing the Consumer's accept method properly

We use generics to allow Types(Integer,Float etc) to be the parameter. When we define a class or something to use Generics we Use these Angular Brackets but when we have to use this type we don't have to use Angular Brackets

Example :-

interface Consumer<T> { //Defining Interface that's why using <>

    void accept(T t); //here this method can accept a parameter of T type

    T returnSomething(int n) //here this method is having return type of T
}

So in your ListPresenter class you are giving two types of return type to the accept method of Consumer interface.

public <T> void accept(ListResponse<T> response)

should be this

public void accept(ListResponse<T> response)

or This if it have a generic return type

public T accept(ListResponse<T> response)

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