JAVA - 지네릭스(Generics) (3)

jodbsgh·2022년 4월 4일
0

💡"JAVA"

목록 보기
38/67

지네릭 클래스의 객체 생성과 사용

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

Box<T>의 객체를 생성할 때는 다음과 같이 한다. 참조변수와 생성자에 대입된 타입이 일치해야 한다.

	Box<Apple> appelBox	= new Box<Apple>();	//ok
    Box<Apple> appleBox = new Box<Grape>(); //에러
    
두 타입이 상속관계에 있어도 마찬가지이다. Apple이 Fruit 의 자손이라고 가정하자.
	Box<Fruit> appelBox	= new Box<Apple>();	//에러, 대입된 타입이 다르다.
    
단, 두 지네릭 클래스의 타입이 상속관계에 있고, 대입된 타입이 같은 것은 괜찮다.
FruitBox는 Box의 자손이라고 가정하자.

	Box<Apple> appleBox = new FruitBox<Apple>(); //ok. 다형성
    
Box<T>의 객체에 'void add(T item)'으로 객체를 추가할 때, 대입된 타입과 다른 타입의
객체는 추가할 수 없다.

	Box<Apple> appleBox = new Box<Apple>();
    appleBox.add(new Apple());	//ok
    appleBox.add(new Grape());	//에러 Apple객체만 추가 가능
    
그러나 타입 T가 'Fruit'인 경우, 'void add(Fruit item)'가 되므로 
Fruit의 자손들은 이 메서드의 매개변수가 될 수 있다. Apple이 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";  }}

class FruitBoxEx1{
	public static void main(String[] args)
    {
    	Box<Fruit> fruitBox = new Box<FruitBox>();
        Box<Apple> appleBox = new Box<AppleBox>();
        Box<Toy>   toyBox = new Box<Toy>();
//      Box<Grape> grapeBox = new Box<Apple>();	//에러, 타입 불일치
        
        fruitBox.add(new Fruit());
        fruitBox.add(new Apple());	//ok, void add (Fruit 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>에는 Apple만 담을 수 없음

		System.out.println(fruitBox);
        System.out.println(appleBox);
        System.out.println(toyBox);
        //main 끝
    }
}

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

실행결과
[Fruit, Apple]
[Apple, Apple]
[Toy]
profile
어제 보다는 내일을, 내일 보다는 오늘을 🚀

0개의 댓글