定义和使用含有泛型的方法和接口

定义和使用含有泛型的方法

定义含有泛型的方法:泛型定义在方法的修饰符和返回值类型之间

格式:

修饰符<泛型>返回值类型方法名(参数列表(使用泛型)){
   方法体;
}

含有泛型的方法,在调用方法的时候确定泛型的数据类型

传递什么类型的参数,泛型就是什么类型

复制代码
    public static void main(String[] args) {
        mehtod01(100);
        mehtod01("字符串");
        mehtod01(5.5);
        mehtod01('a');
    }
    //定义一个含有泛型的方法
    public static <M> void mehtod01(M m){
        System.out.println(m);
    }
复制代码

运行结果:

 

 

 

 

 

 

定义和使用含有泛型的接口

第一种使用方式:定义接口的实现类,实现接口,指定接口的泛型
public interface GenericInterface<I> {
    public abstract void method(I i);
}
复制代码
/**
 * 含有泛型的接口,第一种使用方式:定义接口的实现类,实现接口,指定接口的泛型
 */
public class GenericInterfaceImpl implements GenericInterface<String>{
    @Override
    public void method(String s) {
        System.out.println(s);
    }
}
复制代码
public class DemoGenericInterface {
    public static void main(String[] args) {
        GenericInterfaceImpl genericInterface = new GenericInterfaceImpl();
        genericInterface.method("abc");
    }
}


第二种使用方式:接口使用什么泛型,实现类就是使用什么泛型,类跟着接口走

就相当于定义了一个含有泛型的类,创建对象的视乎确定泛型的类型
public interface GenericInterface<I> {
    public abstract void method(I i);
}
复制代码
/**
 * 含有泛型的接口,第二种使用方式:接口使用什么泛型,实现类就是使用什么泛型,类跟着接口走
 * 就相当于定义了一个含有泛型的类,创建对象的视乎确定泛型的类型
 */
public class GenericInterfaceImpl2<I> implements GenericInterface<I>{

    @Override
    public void method(I i) {
        System.out.println(i);
    }
}
复制代码
public class DemoGenericInterface {
    public static void main(String[] args) {
        GenericInterfaceImpl2<String> impl2 = new GenericInterfaceImpl2<>();
        impl2.method("张三");
        GenericInterfaceImpl2<Integer> impl3 = new GenericInterfaceImpl2<>();
        impl3.method(50);
    }
}

 

posted @   xjw12345  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示