泛型

本文介绍了泛型在Java编程中的应用,通过实例展示了如何使用泛型机制解决类型转换问题,确保代码的安全性和灵活性。文章具体分析了一个泛型类的实现方式,以及其在不同数据类型(如int、float等)上的应用,强调了泛型在处理类型参数时的优越性。

1,泛型的实质是是程序员定义安全的类型。2,ClassCastException异常,“向下转型”操作通常会出现问题,而泛型机制有效的解决了这一问题。

3,下面的例子是泛型的一种应用,对于相加的函数,相加的对象可能是int型,也可能是float型等。通过泛型可以下次解决。

package com.cskaoyan.reflect;

public class ReflectTestMain {

    public static void main(String[] args) throws ClassNotFoundException {
        
        //Calc calc =new Calc(1,3);
           
        Calculor<Integer> calculor   = new Calculor<Integer>(new Integer(1), 3); //自动装箱
        Calculor          myCalculor = new Calculor( 1,2);
        Object x =  myCalculor.getX();
    }
    
    //泛型
}

class Calculor<T>{  //此处T必须是类
    
    T x ;
    T y ;
    public T getX() {
        return x;
    }
    public void setX(T x) {
        this.x = x;
    }
    public T getY() {
        return y;
    }
    public void setY(T y) {
        this.y = y;
    }
    public Calculor(T x, T y) {
        super();
        this.x = x;
        this.y = y;
    }
    public Calculor() {
        super();        
    }    
}

/*class Calc{
    
    int x;
    int y;
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
    public Calc(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

}

class Calc2{
    
    double x;
    double y;
    public double getX() {
        return x;
    }
    public void setX(double x) {
        this.x = x;
    }
    public double getY() {
        return y;
    }
    public void setY(double y) {
        this.y = y;
    }
    public Calc2(double x, double y) {
        super();
        this.x = x;
        this.y = y;
    }
    
}
*/

转载于:https://www.cnblogs.com/yidijimao/p/5170351.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值