제네릭 메서드
- 자료형 매개 변수를 메서드의 매개 변수나 반환 값으로 가지는 메서드이다.
- 자료형 매개 변수가 여러 개일 수 있다.
- 제네릭 클래스가 아니더라도, 메서드를 정의할 때 제네릭 메서드로 구현할 수 있다.
public <T> int method(int parameter) {} // 제네릭 메서드 선언
예제 코드
두 점을 기준으로 사각형을 만들 때, 사각형의 너비를 구하는 메서드를 만들어본다. 각 좌표는 정수인 경우도 있고 실수인 경우도 있기 때문에 제네릭 메서드로 구현한다.
Point.java
좌표를 구현한 제네릭 클래스
package ch09;
public class Point<T, V> { // 자료형 매개변수가 두개인 제네릭 클래스
T x;
V y;
Point(T x, V y) {
this.x = x;
this.y = y;
}
public T getX() {
return x;
}
public V getY() {
return y;
}
}
GenericMethod.java
제네릭 함수 실행부에서 <> 연산자는 안써줘도 실행이 잘 되는 것 같다.
package ch09;
public class GenericMethod {
public static <T,V> double makeRactanle(Point<T,V> p1, Point<T,V> p2) { // 제네릭 메서드 선언부
double left = ((Number)p1.getX()).doubleValue();
double right = ((Number)p2.getX()).doubleValue();
double top = ((Number)p2.getY()).doubleValue();
double bottom = ((Number)p1.getY()).doubleValue();
double width = right - left;
double height = top - bottom;
return width * height;
}
public static void main(String[] args) {
Point<Integer, Double> p1 = new Point<>(0,0.0);
Point<Integer, Double> p2 = new Point<>(10,10.0);
double size = GenericMethod.<Integer, Double>makeRactanle(p1, p2); // 제네릭 함수 실행
System.out.println(size);
}
}
수행 결과
100.0
'Java & Kotlin' 카테고리의 다른 글
[Java 자료구조] 컬렉션 프레임워크 (0) | 2022.02.11 |
---|---|
[Java 자료구조] 제네릭 프로그래밍에서의 자료형 제한 (0) | 2022.02.07 |
[Java 자료구조] 제네릭 프로그래밍 (0) | 2022.02.07 |