Ch12-4~6. 지네릭 다형성
0. 목차
Chapter12. 지네릭스, 열거형, 애너테이션
Ch12 - 4. 지네릭스의 용어
Ch12 - 5. 지네릭 타입과 다형성
Ch11 - 6. 지네릭 타입과 다형성 예제
Ch12 - 1. 지네릭스의 용어
▶ Box<T>
▷ 지네릭 클래스
▷ ‘T의 Box’ 또는 ‘T Box’ 라고 읽음
T
: 타입 변수 또는 타입 매개 변수(T는 타입 문자)Box
: 원시 타입(raw type) 즉, 일반 클래스
▶ 지네릭 클래스 선언
▷ 원시 타입과 타입 변수
▷ 매개 변수화 된 타입
Ch12 - 2. 지네릭 타입과 다형성
▶ 지네릭 타입과 다형성이 일치할 때는?
▷ 참조변수와 생성자가 상속이라도 매개 변수화 된 타입은 일치해야 함
class Product { }
class Tv extends Product { }
class Audio extends Product { }
ArrayList<Tv> list = new ArrayList<Tv>(); // OK 일치
ArrayList<Product> list = new ArrayList<Tv>(); // ERROR 불일치
▷ 지네릭 클래스 간의 다형성은 성립
▷ 여전히 매개 변수화 된 타입은 일치해야 함
List<Tv> list = new ArrayList<Tv>(); // OK 다형성, ArrayList가 List를 구현
List<Tv> list = new LinkedList<Tv>(); // OK 다형성, LinkedList가 List를 구현
▷ 매개 변수의 다형성도 성립
▷ 여전히 매개 변수화 된 타입은 일치해야 함
class Product { }
class Tv extends Product { }
class Audio extends Product { }
ArrayList<Product> list = new ArrayList<Product>();
list.add(new Produc());
list.add(new Tv()); // OK
list.add(new Audio()); // OK
ArrayList<Product> list = new ArrayList<Product>();
Product p = list.get(0);
Tv t = list.get(1);
Audio a = list.get(2);
Ch12 - 3. 지네릭 타입과 다형성 예제
▶ 에러가 나는 이유는?
import java.util.*;
class Product {}
class Tv extends Product {}
class Audio extends Product {}
class Ex12_1 {
public static void main(String[] args) {
ArrayList<Product> productList = new ArrayList<Product>();
ArrayList<Tv> tvList = new ArrayList<Tv>();
ArrayList<Product> tvList2 = new ArrayList<Tv>(); // 컴파일 에러1
List<Tv> tvList3 = new ArrayList<Tv>();
productList.add(new Tv());
productList.add(new Audio());
tvList.add(new Tv());
tvList.add(new Tv());
printAll(productList);
printAll(tvList); // 컴파일 에러2
}
public static void printAll(ArrayList<Product> list) {
for (Product p : list)
System.out.println(p);
}
}
▷ 매개 변수화 된 타입은 상속 관계 불가
ArrayList<Product> tvList2 = new ArrayList<Tv>();
printAll(tvList) -호출→ public static void printAll(ArrayList<Product> list)
tvList<tv> -<Product>와 <Tv>?→ ArrayList<Product> tvList = 불가능
▷ 제네릭 클래스 간의 다형성은 성립
List<Tv> tvList3 = new ArrayList<Tv>();
그래서 이건 가능