제너릭 메서드란?
: 자료형 매개변수를 메서드의 매개변수나 반환 값으로 가지는 메서드
: 자료형 매개 변수가 하나 이상인 경우도 있다.
: 제네릭 클래스가 아니어도 내부에 제네릭 메서드는 구현하여 사용할 수 있음
: public <자료형 매개 변수> 반환형 메서드 이름(자료형 매개변수...){}
예시
package Basic_Grammar.chap4.ch06Generic.Test03_GenericMethod;
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 void setX(T x) {
this.x = x;
}
public V getY() {
return y;
}
public void setY(V y) {
this.y = y;
}
}
리턴타입앞에 자료형 매개변수를 사용해 준다.
package Basic_Grammar.chap4.ch06Generic.Test03_GenericMethod;
public class GenericMethod {
public static <T,V> double makeRectangle(Point<T,V> p1,Point<T,V>p2){
double left=((Number)p1.getX()).doubleValue();
double right=((Number)p2.getX()).doubleValue();
double top=((Number)p1.getY()).doubleValue();
double bottom=((Number)p2.getY()).doubleValue();
double width=right-left;
double height=bottom-top;
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 rect=GenericMethod.<Integer,Double>makeRectangle(p1,p2);
System.out.println("두 점으로 만들어진 사각형 넓이는 "+rect);
}
}
실행 결과
'JAVA > Java2021-2' 카테고리의 다른 글
ArrayList를 이용하여 구현 (0) | 2021.10.09 |
---|---|
자바에서 제공되는 자료구조 구현 클래스 (Collection 프레임워크) (0) | 2021.10.09 |
제네릭(Generic) - <T extends 클래스> 이용 (0) | 2021.10.09 |
제네릭(Generic) -Collections 프레임워크에 많이 사용된다. (0) | 2021.10.08 |
자바와 자료구조 (선형자료구조, 비선형자료구조, 매핑형자료구) (0) | 2021.10.08 |