class Box<B> {
T item;
void setItem(T item) { this.item = item; }
T getItem() { return item; }
}
⇒ Object를 모두 T로 바꿔 선언
static 멤버에 타입변수 T를 사용할 수 없음 ⇒ why? 모든 객체에 동일하게 동작해야하기 떄문import java.util.ArrayList;
class Fruit { public String toString() { return "Fruit"; } }
class Apple extends Fruit { public String toString() { return "Apple"; } }
class Grape extends Fruit { public String toString() { return "Grape"; } }
class Toy { public String toString() { return "Toy"; } }
class FruitBoxEx1 {
public static void main(String[] args) {
Box<Fruit> fruitBox = new Box<Fruit>();
Box<Apple> appleBox = new Box<Apple>();
// Box<Grape> grapeBox = new Box<Apple>(); // 에러. 타입 불일치
Box<Toy> toyBox = new Box<Toy>();
fruitBox.add(new Fruit());
fruitBox.add(new Apple()); // OK. void add(Fruit item)
appleBox.add(new Apple());
appleBox.add(new Apple());
// appleBox.add(new Toy()); // 에러. Box<Apple>에는 Apple만 담을 수 있음
toyBox.add(new Toy());
// toyBox.add(new Apple()); // 에러. Box<Toy>에는 Apple을 담을 수 없음
System.out.println(fruitBox);
System.out.println(appleBox);
System.out.println(toyBox);
} // main
}
class Box<T> {
ArrayList<T> list = new ArrayList<T>();
void add(T item) { list.add(item); }
T get(int i) { return list.get(i); }
int size() { return list.size(); }
public String toString() { return list.toString(); }
}
<T extends Fruit>? 로 표현해서 어떠한 타입도 될 수 있게 표현함<? extends T> : T와 그 자손들만 가능<? super T> : T와 그 조상들만 가능<?> : 제한 없음