Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java method generics implementing interface

Tags:

java

generics

What is wrong with this code?

public interface FileProccessor {
    public <RT> RT setHeader(RT header);
}

public class AProcessor implements FileProccessor {

    @Override
    public Header setHeader(Header header) {
        return null;
    }
}

Compilator is complaining: The method setHeader(Header) of type AProcessor must override or implement a supertype method

Edit: Thanks. I got confused because I wanted multiple methods with different types. Now I realized a can add as many parametrized types as I want in class level. Like FileProcessor<T, F, M>.

like image 977
braincell Avatar asked Feb 19 '23 00:02

braincell


2 Answers

Your interface declaration specifies that all implementations of the interface will provide a generic method with this signature:

public <RT> RT setHeader(RT header);

In other words, the caller would be able to pass an object of any type, and get back an object of the same exact type.

You implementation declaration, on the other hand, limits the user to a single type, i.e. the Header. That's why the compiler is complaining about inability to override.

The trick would work if the interface were generic, and a type implementing it was implementing a generic instance, like this:

public interface FileProccessor<T> {
    public T setHeader(T header);
}

public class AProcessor implements FileProccessor<Header> {
}
like image 186
Sergey Kalinichenko Avatar answered Feb 27 '23 10:02

Sergey Kalinichenko


I think you wanna do this:

public interface FileProccessor<RT, RX> {
    public RT setHeader(RT header);
    public RX setFooter(RX footer);
}

public class AProcessor implements FileProccessor<Header, Footer> {

    @Override
    public Header setHeader(Header header) {
        return null;
    }

    @Override
    public Footer setFooter(Footer footer) {
        return null;
    }
}
like image 27
Tim Büthe Avatar answered Feb 27 '23 10:02

Tim Büthe