2015年9月23日 星期三

Java 泛型概念

泛型的功能:
public class Shirt {
   private int shirtID = 0;

    public int getShirtID() {
        return shirtID;
    }

    public void setShirtID(int shirtID) {
        this.shirtID = shirtID;
    } 
}

public class CacheAny {
    private T t;
    public void add(T t){
        this.t = t;
    }
    public T get(){
        return this.t;
    }
}

public class Demo {
    public static void main(String[] args){
        CacheAny myMessages = new CacheAny<>();
        myMessages.add("This is my Shirt!");
        System.out.println(myMessages.get().toString());
        
        CacheAny myShirt = new CacheAny<>();
        myShirt.add(new Shirt());
        myShirt.get().setShirtID(123456);
        System.out.println("Shirt ID :" + myShirt.get().getShirtID());
    }
}