YJ의 새벽

JAVA (제네릭 <?>, 형변환) 본문

SelfStudy/JAVA

JAVA (제네릭 <?>, 형변환)

YJDawn 2023. 2. 5. 23:51

 

--하나의 참조변수로 대입된 타입이 다른 객체를 참조 가능.

 

 

    EX )))

 

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 Juice{
	String name;
	Juice(String name)       {this.name=name+"Juice";}
	public String toString() {return name;}
}
class FruitBox <T extends Fruit> 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);}
	ArrayList<T> getList() { return list;}
	int size()       {return list.size();}
	public String toString() {return list.toString();}
}
class Juicer{
	static Juice makeJuice(FruitBox <? extends Fruit> box) {
		String tmp="";
		for(Fruit f : box.getList())
			tmp+= f+" ";
		return new Juice(tmp);
	}
}
public class Example {
	public static void main(String[] args) {
		FruitBox<Fruit> fruitBox=new FruitBox<Fruit>();		
		FruitBox<Apple> appleBox=new FruitBox<Apple>();	      
			
		fruitBox.add(new Apple());
		fruitBox.add(new Grape());
		appleBox.add(new Apple());
		appleBox.add(new Apple());
		
		System.out.println(Juicer.makeJuice(fruitBox));  --Apple Grape Juice
		System.out.println(Juicer.makeJuice(appleBox));  --Apple Apple Juice
	}		
}

 

 

**제네릭 타입의 형변환 .

 

제네릭 타입과 원시 타입간의 형변화는 바람직 하지 않다.

 

public class Example {
	public static void main(String[] args) {
		Box b = new Box<String>();
		Box<String> bStr = null;
		
		b=(Box)bStr;           //  Box<String> --> Box가능 , but 경고
		bStr = (Box<String>)b; //  Box --> Box<String> 가능 , but 경고
		}		
	}

 

 

 

 

 

 

 

 

'SelfStudy > JAVA' 카테고리의 다른 글

JAVA (애너테이션)  (0) 2023.02.06
JAVA (열거형)  (0) 2023.02.06
JAVA (제네릭)  (0) 2023.02.04
JAVA (Collections), 컬렉션 요약정리.  (0) 2023.02.03
JAVA (HashMap)  (2) 2023.02.03
Comments