ArrayList<? extends Product> list = new ArrayList<Tv>(); // OK
ArrayList<? extends Product> list = new ArrayList<Audio>(); // OK
ArrayList<Product> list = new ArrayList<Tv>(); // 에러, 대입된 타입 불일치
와일드 카드의 세가지 용법
메서드의 매개변수에 와일드 카드를 사용
static Juice makeJuice(FruitBox<? extends Fruit> box) {
//Fruit과 그 자손을 받을 수 있다.
. . .
. . .
}
static <T> void sort(List<T> list, Comparator<? super T> c)
class FruitBox<T> { // 지네릭 클래스
static<T> void sort(List<T> list, Comparator<? super T> c) {
// 지네릭 메소드
// 클래스와 메소드의 타입문자가 일치하지만 다른 타입변수이다.
// 메소드의 타입변수는 메소드 안에서만 사용
// instance variable, local variable의 차이를 생각하면 된다.
}
}
FruitBox<Fruit> fruitBox = new FruitBox<Fruit>();
FruitBox<Apple> appleBox = new FruitBox<Apple>();
. . .
Juicer.<Fruit>makeJuice(fruitBox));
Juicer.<Apple>makeJuice(appleBox));
static <T extends Fruit> Juice makeJuice(FruitBox<T> box) {
//Fruit 또는 그 자손만 대입 가능
. . .
. . .
}