Language/JAVA
[JAVA]제네릭(Generic)프로그래밍
바까
2020. 7. 2. 17:59
반응형
제네릭프로그래밍
-
변수의 선언이나 메서드의 매개변수를 하나의 참조 자료형이 아니라 여러 자료형으로 변환할 수 있도록 프로그래밍을 하는 방식.
-
실제 사용되는 참조자료형으로의 변환은 컴파일러가 검증하므로 안정적인 프로그래밍 방식이다.
-
컬렉션 프레임워크에서 많이 사용되고 있다.
자료형 매개 변수 T
-
Type의 의미로 T를 많이 사용한다.
-
*<T>에서 <>는 다이아몬드 연산자
-
static 키워드는 T에 사용할 수 없다.
-
ArrayList<String> list = new ArrayList<>(); 다이아몬드 연산자 내부에서 자료형은 생략가능
[실습] Powder클래스 정의
//Powder 클래스를 정의
public class Powder {
//메서드(멤버 함수)를 정의
public void doPrinting() {
System.out.println("Powder 재료로 출력합니다.");
}
public String toString() {
return "재료는 Powder 입니다.";
}
}
[실습] Plastic 클래스 정의
//Plastic 클래스를 정의
public class Plastic {
//메서드(멤버 함수)를 정의
public void doPrinting() {
System.out.println("Plastic 재료로 출력합니다.");
}
public String toString() {
return "재료는 Plastic 입니다.";
}
}
[실습]GenericPrinter<T>클래스 정의
//GenericPrinter<T>클래스를 정의
public class GenericPrinter<T> {
//T 자료형을 필드(멤버변수)를 선언
private T material;
//get(), set() 메서드를 정의
public T getMaterial() {
return material;
}
public void setMaterial(T material) {
this.material = material;
}
//재료를 출력하는 메서드를 정의
public String toString() {
//반환값은 객체를 생성할 때 구분이된다. [Powder or Plastic]
return material.toString();
}
}
[실습] 메인메서드
public class GenericPrinterTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Powder 형으로 GenericPrinter 클래스를 생성
GenericPrinter<Powder> powderPrinter = new GenericPrinter<Powder>();
powderPrinter.setMaterial(new Powder());
Powder powder = powderPrinter.getMaterial();
System.out.println(powderPrinter); //재료는 Powder 입니다.
//Plastic 형으로 GenericPrinter 클래스를 생성
GenericPrinter<Plastic> plasticPrinter = new GenericPrinter<Plastic>();
plasticPrinter.setMaterial(new Plastic());
Plastic plastic = plasticPrinter.getMaterial();
System.out.println(plasticPrinter); //재료는 Plastic 입니다.
}
}
*
-GenericPrinter<Powder>: 제네릭 자료형(Generic Type), 매개변수화된 자료형(parameterized type)
-Powder: 대입된 자료형
반응형