Hello

Java 제한된 지네릭 클래스, 지네릭스의 제약

by 볼빵빵오춘기

제한된 지네릭 클래스

  • extends로 대입할 수 있는 타입을 제한한다.
더보기

⇒ <T>만 있었을 경우 모든 타입이 가능했으나 <T extends Fruit> extends 키워드를 넣어줌으로써 Fruit의 자손만 대입이 가능(Fruit도 대입가능)

  • 인터페이스인 경우에도 extends를 사용한다.
더보기

⇒ implements를 쓸 것같은데 extends를 쓴다.

 

예제 코드

import java.util.*;
import static java.util.Collections.*;

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 {}

public class Try {
	public static void main(String[] args) {
		FruitBox<Fruit> fruitBox = new FruitBox<Fruit>();
		FruitBox<Apple> appleBox = new FruitBox<Apple>();
		FruitBox<Grape> grapeBox = new FruitBox<Grape>();
//		FruitBox<Grape> grapeBox = new FruitBox<Apple>(); // 에러. 타입 불일치
//		FruitBox<Toy>   toyBox   = new FruitBox<Toy>();   // 에러.

		fruitBox.add(new Fruit());
		fruitBox.add(new Apple());
		fruitBox.add(new Grape());
		appleBox.add(new Apple());
//		appleBox.add(new Grape());  // 에러. Grape는 Apple의 자손이 아님
		grapeBox.add(new Grape());

		System.out.println("fruitBox-"+fruitBox);
		System.out.println("appleBox-"+appleBox);
		System.out.println("grapeBox-"+grapeBox);
	}
}


class FruitBox<T extends Fruit & Eatable> extends Box<T> {}
// 인터페이스를 같이 쓸때는 & 를 써야한다.

class Box<T> {
	ArrayList<T> list = new ArrayList<T>(); // item을 저장할 list
	void add(T item) { list.add(item);     } // 박스에 item을 추가
	T get(int i)     { return list.get(i); } // 박스에서 item을 꺼낼때
	int size()       { return list.size(); }
	public String toString() { return list.toString();}
}
더보기

이미지로 표현하자면 아래와 같다. 

 

지네릭스의 제약

  • 타입 변수에 대입은 인스턴스 별로 다르게 가능하다.
  • static멤버에 타입 변수 사용하지 못 한다.
더보기

⇒ 위에 인스턴스 별로 다르게 가능한 기능이므로

  • 배열 생성할 때 타입 변수 사용하지 못 하고 타입 변수로 배열 선언은 가능하다.
더보기

⇒ new연산자 다음에 T사용 불가라 외우기

블로그의 정보

Hello 춘기's world

볼빵빵오춘기

활동하기