泛型

泛型


前言

  1. 本质是参数化类型,把类型作为参数传递
  2. 常见形式有泛型类、泛型接口、泛型方法
  3. 语法 T成为类型占位符,表示一种引用类型,可以写多个逗号隔开
  4. 好处
  • 提高代码重用性
  • 防止类型转换异常,
  • 提高代码安全性

提示:以下是本篇文章正文内容,下面案例可供参考

一、泛型类

语法:public class A{ …}

public class FX <T>{
    T t;//创建变量
    public void show(T t1){//作为方法参数
        System.out.println(t1);
    }
    public T get(){//作为方法返回值
        return t;
    }
}
public class test5 {
    public static void main(String []arg){
        FX<String> a = new FX<>();
        a.t = "hello FX";
        a.show("hello FX1");
        String b = a.get();
        System.out.println(b);
    }
}
/*
hello FX1
hello FX
 */

二、泛型接口

语法:interfaces A{…};
不可定义泛型静态常量

public interface test<T> {
    void A();
    T B();
}

可继续实现为泛型类

public class test3<T> implements test<T>{
    T t;
    public void A() {
        System.out.println(t);
    }
    public T B() {
        return t;
    }
}
public class test1 implements test<String>{
    public void A() {
        System.out.println("大帅哥");
    }
    public String B() {
        return "小帅哥";
    }
}
 public static void main(String []args){
        test1 a =new test1();
        String b=a.B();
        a.A();
        System.out.println(b);
    }
}
//大帅哥
//小帅哥

三、泛型方法

语法:public T show(T t){ }

public class MyGenericMethod{
  //泛型方法
  public <T> T show(T t){
    sout("泛型方法" + t);
    return t;
  }
}

//调用
MyGenericMethod myGenericMethod = new MyGenericMethod();
myGenericMethod.show("字符串");// 自动类型为字符串
myGenericMethod.show(200);// integer类型
myGenericMethod.show(3.14);// double类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值