클래스와 메서드에 선언 가능
class Box<T>{
T item;
void setItem(T item) {this.item = item; }
T getItem() {return item; }
}
class Box<T> {}
Box<Apple> appleBox = new FruitBox<Apple>();
Box<Apple> appleBox = new Box<>();
class FruitBox<T extends Fruit> {
ArrayList<T> list = new ArrayList<T>();
}
interface Eatable{}
class FruitBox<T extends Eatable> {}
}
class FruitBox<T extends Fruit & Eatable> {...}
- <? extends T> 와일드 카드의 상한 제한. T와 그 자손들만 가능
- <? super T> 와일드 카드의 하한 제한. T와 그 조상들만 가능
- <?> 제한 없음. 모든 타입이 가능. <? extends Object>와 동일
static <T> void sort(List<T> list, Comparator<? super T> c)
static <T extends Fruit> Juice makeJuice(FruitBox<T> box) {
String tmp = "";
for(Fruit f : box.getList()) {
tmp += f + " ";
}
return new Juice(tmp);
}
//호출
FruitBox<Fruit> fruitBox = new FruitBox<Fruit>();
Juicer.<Fruit>makeJuice(fruitBox);
Juicer.makeJuice(fruitBox);
Box box = null;
Box<Object> objBox = null;
box = (Box)objBox;
objBox = (Box<Object>) box;
Box<String> strBox = null;
Box<Object> objBox = null;
objBox = (Box<Object>)strBox;
strBox = (Box<str>) objBox;
static Juice makeJuice(FruitBox<? extends Fruit> box){...}
FruitBox<? extends Fruit> box = new FruitBox<Apple>();