泛型定义类的简单介绍。

package com.aaa.test;
/*
 * 泛型的作用:
    A:提高了程序的安全性(泛型在集合里的使用)
    B:将运行期遇到的问题转移到了编译期
    C:省去了类型强转的麻烦
    D:提高了代码的重用性,实现代码的公共的封装

 * •泛型方法
    –把泛型定义在方法上
    –格式:public <泛型类型> 返回类型 方法名(泛型类型 .)
 * 
 */

import java.util.ArrayList;
import java.util.List;

public class Demo11 <E>{
    private int id;
    private String name;
    /**
     * @return the id
     */
    public int getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Demo11 [id=" + id + ", name=" + name + "]";
    }
    
    public static void main(String[] args) {
        Demo11<Object> demo11 = new Demo11<>();
        
        //使用泛型  添加数据快捷  
        List<Object>list=new ArrayList<>();
        list.add(4654);
        list.add("哈哈");
        
        System.out.println(list);
    }
    
    

}

二、泛型定义接口

package com.aaa.test;
/*
 * 泛型定义在接口
    –把泛型定义在接口上
    –格式:public  interface 接口名<泛型类型1…>
    
    public interface FanXingDingYiJieKou <E>{
            int add();
}
 * 
 * 泛型实现接口
 * 
 */
public class Demo10<E> implements FanXingDingYiJieKou<E>{

    @Override
    public int add(E e) {
        // TODO Auto-generated method stub
        return 0;
    }
    public static void main(String[] args) {
        Demo10<Object> d = new Demo10<>();
        
        // 前父后子
        FanXingDingYiJieKou<Object> f = new Demo10<>();
         d.add(1);
         f.add(1);
        
    
        
    }

}

猜你喜欢

转载自www.cnblogs.com/ZXF6/p/11129035.html