Getting compile error while implementing a simple Generic methods in java

krishna Prasad :

Getting compile error while implementing a Generic methods in java

My Generic interface :

interface GenericInterface {
    <T> T genericMethod(T t);
}

Below is my implementation which is throwing error:

public class GenericImplementation implements GenericInterface {

    // Not working
    @Override
    public Double genericMethod(Double t) {
        System.out.println("Trying to implement generic method with return T and method args T as well ");
        return t*4.3;
    }

}

Any help will be highly appreciate in advance, I am missing something in Generic class implementation might be.

Andy Turner :

If you want your implementation to be for a specific type, the type variable has to be declared on the class/interface:

interface GenericInterface<T> {
    T genericMethod(T t);
}

and implement like:

public class GenericImplementation implements GenericInterface<Double> {

<T> T genericMethod(T t) doesn't mean an implementation can be for any type, it means it has to be for all types. You can't restrict it to one type.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112026&siteId=1