class Box<T> {
ArrayList<T> list = new ArrayList<T>();
void add(T item) { list.add(item); }
T get(int i) { return list.get(i); }
ArrayList<T> getList() { return list; }
int size() { reutrn list.size(); }
public String toString() { return list.toString(); }
}
위와 같은 클래스가 정의 되어 있다고 가정하고 이 객체를 생성하고 사용 해보려 한다.
참조변수와 생성자에 대입된 타입이 일치해야한다.
Box<Apple> appleBox = new Box<Apple>(); // OK
Box<Apple> appleBox = new Box<Grape>(); // 에러
상속관계여도 타입변수는 일치해야한다 예를들어 Apple이 Fruit의 자손이라고 해도 얄짤 없다.
타입변수를 지정할 때는 항상 일치해야 된다고 기억하자.
Box<Fruit> appleBox = new Box<Apple> // 에러
추정이 가능한 경우에는 타입 생략이 가능하다
Box<Apple> appleBox = new Box<>; // OK
Apple이 Fruit의 자손이라고 가정하면
'void add(Fruit item)'이 되므로 Fruit의 자손들은 이 메서드의 매개변수가 될 수 있다.
Box<Fruit> fruitBox = new Box<Fruit>();
fruitBox.add(new Fruit()); // Ok
fruitBox.add(new Apple()); // Ok. void add(Fruit item);
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"; } }
public class FruitBox {
public static void main(String[] args) {
Box<Fruit> fruitBox = new Box<>();
Box<Apple> appleBox = new Box<>();
Box<Toy> toyBox = new Box<>();
// Box<Apple> grapeBox = new Box<Grape>(); // 에러 타입 불일치
fruitBox.add(new Fruit());
fruitBox.add(new Apple()); // Ok. void add(Frit 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>에는 Toy만 담을 수 있음.
System.out.println(fruitBox);
System.out.println(appleBox);
System.out.println(toyBox);
}
}
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();
}
}
댓글