温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java泛型接口怎么实现

发布时间:2026-09-10 06:43:16 来源:亿速云 阅读:87 作者:小樊 栏目:编程语言

在 Java 中,**泛型接口(Generic Interface)**是指带有类型参数(如 <T>)的接口。实现泛型接口主要有 两种方式

  1. 实现时指定具体类型
  2. 实现时继续保留泛型

下面通过示例详细说明。


一、定义泛型接口

public interface Repository<T> {
    void save(T t);
    T getById(int id);
}

二、方式一:实现时指定具体类型(最常用)

在实现类中直接给定泛型的具体类型,比如 StringUser 等。

示例

public class UserRepository implements Repository<User> {

    @Override
    public void save(User user) {
        // 保存用户
    }

    @Override
    public User getById(int id) {
        return new User();
    }
}

✅ 优点:

  • 使用简单
  • 编译期类型安全
  • 不需要再写泛型

三、方式二:实现时继续保留泛型

实现类本身也定义为泛型类。

示例

public class GenericRepository<T> implements Repository<T> {

    @Override
    public void save(T t) {
        // 保存
    }

    @Override
    public T getById(int id) {
        return null;
    }
}

使用方式:

Repository<String> repo = new GenericRepository<>();

✅ 优点:

  • 更灵活
  • 适用于通用组件(如 DAO、工具类)

四、多个泛型参数

public interface Pair<K, V> {
    K getKey();
    V getValue();
}
public class StringIntPair implements Pair<String, Integer> {
    public String getKey() { return "key"; }
    public Integer getValue() { return 1; }
}

五、泛型接口 + 泛型方法(补充)

接口中也可以有泛型方法:

public interface Converter {
    <T> T convert(Object obj);
}

六、常见注意点

  1. 实现接口时必须与接口的泛型一致
  2. 不能写成:
    class A implements Repository {} // ❌ 原始类型(不推荐)
    
  3. 泛型只在编译期有效(类型擦除)

如果你有具体场景(比如 DAO、Spring、Comparator、Function 接口等),我可以给你更贴合的示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI