푸린세스

지네릭 타입의 형변환2 본문

카테고리 없음

지네릭 타입의 형변환2

푸곰주 2022. 3. 26. 11:48
package ex12;

import java.util.ArrayList;

class Fruit implements Eatable{
	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";}}

interface Eatable{}
class Ex12_3 {

	public static void main(String[] args) {
		
		FruitBox<Fruit> fbox = new FruitBox<Fruit>();
		FruitBox<Apple> abox = new FruitBox<Apple>();
		//일치하는게 정석.
		
		FruitBox<? extends Fruit> f2box = new FruitBox<Fruit>();
		FruitBox<? extends Fruit> a2box = new FruitBox<Apple>();
		//형변환이 생략되어있다는 뜻
		
		FruitBox<? extends Fruit> f22box =(FruitBox<? extends Fruit>) new FruitBox<Fruit>();
		//좌변과 우변이 타입불일치 , 대입된 지네릭타입이 다르다.
		//형변환 필요.
		//FruitBox<Apple> -> FruitBox<? extends Fruit>  가능
		
		//FruitBox<? extends Fruit> -> FruitBox<Apple> 가능? 가능하다. but생략불가라 꼭 써줘야함..****
		//FruitBox<Apple> a3box = (FruitBox<Apple>) new FruitBox<? extends Fruit>();
		//위의 경우 new연산자 뒤에 T오면 안됨. 와일드카드도올수없음?
		FruitBox<Apple> a33box = (FruitBox<Apple>)a2box; //OK.경고발생
		//a2box 타입이 명확하지 않는 와일드 카드 -> a33box 명확한타입으로 바꾸려고 하니까..
		//형변환은 항상 () 형변환써주면된다.
		//생략했는데 에러안나면 생략가능한거고, 생략했는데 에러나면 필요한것임..
		
	}

}


class FruitBox<T extends Fruit & Eatable> extends Box<T>{}

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();}
	
	
}