2024.05.31. FRI <D + 10>, Generics (제네릭스)
A. Generics (제네릭스)
class Box {
Object item; => 변수
void setItem(Object item) {
this.item = this;
}
Object getItem() {return item;}
}
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);
}
}