【为什么使用泛型?】

package com.yjf.esupplier.common.test;

/**
 * @author shusheng
 * @description
 * @Email [email protected]
 * @date 2018/12/13 14:46
 */
public class ObjectToolDemoOne {
    /**
     *早期的时候,我们使用 Object 来代表任意的类型。
     *向上转型是没有任何问题的,但是在向下转型的时候其实隐含了类型转换的问题。
     *也就是说这样的程序其实并不是安全的。所以 Java 在 JDK5 后引入了泛型,提高程序的安全性。
     */
    public static void main(String[] args) {
        ObjectToolOne ot = new ObjectToolOne();
        ot.setObj(new Integer(30));
        // ClassCastException
        String ss = (String) ot.getObj();
        System.out.println("姓名是:" + ss);
    }

}

class ObjectToolOne {
    private Object obj;

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }
}

猜你喜欢

转载自www.cnblogs.com/zuixinxian/p/11275033.html