java方法泛型实现接口 [英] java method generics implementing interface

查看:1364
本文介绍了java方法泛型实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码有什么问题?

  public interface FileProccessor {
public< RT> RT setHeader(RT头);


公共类AProcessor实现FileProccessor {

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


Compilator抱怨说:方法setHeader头部)类型的AProcessor必须重写或实现超类型方法 b
$ b

编辑:
谢谢。我很困惑,因为我想要多种不同类型的方法。
现在我意识到可以在课堂级别添加尽可能多的参数化类型。与 FileProcessor< T,F,M>

解决方案

声明指定接口的所有实现都将为此签名提供一个通用方法:

  public< RT> RT setHeader(RT头); 

换句话说,调用者可以传递任何类型的对象,然后取回另一方面,您的实现声明将用户限制为单一类型,即 Header code>。这就是为什么编译器抱怨无法覆盖。



如果接口是通用接口,并且实现它的类型实现了一个通用实例,

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

公共类AProcessor实现FileProccessor< Header> {
}


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>.

解决方案

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> {
}

这篇关于java方法泛型实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆