JAVA-Generics(5)


ムカデ形変換

  • ギネスタイプと元のタイプとの間の変形は望ましくない.
  • Box<Object> objBox = null;
    Box box = (Box)objBox;		//ok. 지네릭타입 -> 원시타입.   경고발생
    objBox = (Box<Object>)box;	//ok. 원시타입   ->지네릭 타입. 경고발생
    Genericタイプとnon-genericタイプの間のタイプ変換は常に可能である.警告だけが発生します.
    Box<Object> objBox = null;
    Box<String> strBox = null;
    
    objBox = (Box<Object>)strBox;	//에러. Box<String> -> Box<Object>
    strBox = (Box<String>)objBox;	//에러. Box<Object> -> Box<String>
  • ワイルドカードタイプはGenericタイプ
  • に変換可能
    Box<Object>			objBOX = (Box<Object>) new Box <String>();	//에러, 형변환 불가능
    Box<? extends Object> wBox = (Box<? extends Object>)new Box<String>();	//ok
    Box<? extends Object> wBox = new Box<String>();
    
    //매개변수로 FruitBox<Fruit>, FruitBox<Apple>, FruitBox<Grape> 등이 가능
    static Juice makeJuice(FruitBox<? extends Fruit> box){ ... }
    
    FruitBox<? extends Fruit> box = new FruitBox<Fruit>();	//ok
    FruitBox<? extends Fruit> box = new FruitBox<Apple>();	//ok