JAVA
190715 Generics 예제
猫猫
2019. 7. 15. 10:40
반응형
package prj190715;
import java.util.*;
class Box<T>{
ArrayList<T> list = new ArrayList<T>();
void add(T item) { list.add(item); } //list.add() 파라미터로 추가하고자하는 객체를 넘김.
T get ( int i ) { return list.get(i); }
ArrayList<T> getList() { return list; }
int size() { return list.size(); }
public String toString() { return list.toString(); }
}
class Fruit {
public String toString() {//리턴타입 String, toString 이라는 메소드 만든거.
return "Fruit";
}
}
class Apple extends Fruit {
public String toString() {
return "Apple extends fruit ";
}
}
class Grape extends Fruit {
public String toString() {
return "Grape extends fruit";
}
}
class Toy {
public String toString() {
return "Toy";
}
}
public class GenericsTest {
public static void main(String[] args) {
Box<Fruit> fruitBox = new Box<Fruit>();
Box<Apple> appleBox = new Box<Apple>();
Box<Toy> toyBox = new Box<Toy>();
//Box <Grape> grapeBox = new Box<Apple>(); //에러 타입 불일치.
fruitBox.add(new Fruit());
fruitBox.add(new Apple()); //가능, void add(T item)
fruitBox.add(new Grape());//extends 관계에선 부모가 자식 갖다 쓸수있어서 가능.
// appleBox.add(new Toy()); //error. Box<Apple>에는 Apple만 담을수 있다.
toyBox.add(new Toy());
// toyBox.add(new Apple()); //error. Box<Toy>에는 Appple을 담을수 없다.
System.out.println(fruitBox);
System.out.println(appleBox);
System.out.println(toyBox);
}
}
결국은 다형성이다.
다형성에 의거하여 부모들은 자식거 갖다 쓸 수 있으니까(? 묘하게 현실적)
box generics type이라 한들, 못 갖다 쓰진 않는다는 것.
반응형