JAVA Programming

Growing_HJ·2024년 5월 31일

일기장

목록 보기
17/51

2024.05.31. FRI <D + 10>, Generics (제네릭스)
A. Generics (제네릭스)

  • 다양한 타입의 객체들을 다루는 메소드나 컬렉션 클래스에 컴파일시의 타입 체크를 해주는 기능.
  • 인스턴스별로 원하는 타입을 지정해서 사용하므로, 제네릭스는 인스턴스 별로 다르게 동작되도록 만들려고 하는 자바의 기능.
    A-1. Generics의 장점
  • 타입의 안정성을 제공하고, 타입체크와 형변환을 생략할 수 있다.
    ex) 일반 클래스를 Generics로 바꿔보자.
class Box {
 	 Object item; => 변수
     void setItem(Object item) {
		this.item = this;
        } 
 	Object getItem() {return item;}
 }
  • Generics logic)
 class Box <T> { //Box <T> :제네릭 클래스, Box: 원시타입
 	 T item; => T -> 타입 변수 
 	 void setItem(T item) {
     this.T = this;
	} 
 	 T getItem() {return item;}
 }

A-2. Generics의 사용제한
1. static 멤버에 타입변수 를 사용할 수 없다.
2. 제네릭스 타입의 배열을 생성할 수 없다.
3. instanceof 연산자, new 연산자에서 타입변수 를 피연산자로 사용할 수 없다.
4. 제네릭스는 인스턴스 별로 다르게 동작되도록 만들려고 하는 자바의 기능.

// 제네릭스 클래스를 생성해보자.
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(); }
}

class Fruit {public String toString() {return "Fruit";} }
class Apple extends Fruit {public String toString() {return "Apple";} }
class Grape extends Fruit {public String toString() {return "Garpe";} }
class Toy {public String toString() {return "Toy";}}

public class GenericsEx1 {
	public static void main(String[] args) {
		Box<Fruit> fruitBox = new Box<Fruit>();
		Box<Apple> appleBox = new Box<Apple>();
		Box<Grape> grapeBox = new Box<Grape>();
		Box<Toy> toyBox = new Box<Toy>();
		
		fruitBox.add(new Fruit());
		fruitBox.add(new Apple());
		fruitBox.add(new Grape());
		
		appleBox.add(new Apple());
		System.out.println(fruitBox);
		System.out.println(appleBox);
		System.out.println(grapeBox);
	}

}

0개의 댓글