제한된 Generic class 란?
class FruitBox<T extends Fruit> {
ArrayList<T> list = new ArrayList<T>();
}
FruitBox<Apple> appleBox = new FruitBox<Apple>();
FruitBox<Toy> toyBox = new FruitBox<Toy>();
interface Eatable { }
class FruitBox<T extends Eatable> { }
- 인터페이스를 같이 사용할때 implements 대신 &로 표현
class FruitBox<T extends Fruit & Eatable> extends Box<T> {}
Generics의 제약
- 타입 변수에 대입은 인스턴스 별로 다르게 가능
Box<Apple> appleBox = new Box<Apple>();
Box<Grape> grapeBox = new Box<Grape>();
- static 멤버에 타입변수 사용 불가
(모든 인스턴스에 공통이기 때문)
class Box<T> {
static T item;
static int compare(T t1, T t2){ ... }
}
- 배열 생성할 때 타입 변수 사용불가, 타입 변수로 배열 선언은 가능
new 연산자는 타입이 확정되어야 하기 때문
class Box<T> {
T[] itemArr ;
T[] toArray() {
T[] tmpArr = new T[itemArr.length];
. . .
}