java泛型的必要性(为什么需要泛型)

/**
 * 2018.8.6
 * 作者:小孟鱼
 * 功能:泛型的必要性(为什么需要泛型)

*好处:编译的时候检查类型安全,并且所有的强制类型转换都是自动和隐式的,提高代码的重用率
 */
package com.test;

import java.util.ArrayList;

public class Fanxinlei {
        public static void main(String[] args) {
            ArrayList<Dog> al=new ArrayList<Dog>();
            //创建了一只狗
            Dog dog1=new Dog();
            //放入到集合中
            al.add(dog1);
            //取出这只狗
            //Dog temp=(Dog)al.get(0);
            Dog temp=al.get(0);
            //Cat temp=(Cat)al.get(0);错误的,编译器会报错(类型转换出错)
            }
}
class Cat{
    private String color;
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    private int age;
    
}
class Dog{
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    private int age;
}

猜你喜欢

转载自blog.csdn.net/weixin_42133768/article/details/81447946