제한된 타입 파라미터
상속 및 구현 관계를 이용해서 타입을 제한
puglic <T extends 상위타입> 리턴타입 메소드(매개변수, ...) { ... }
상위 타입은 클래스 뿐만 아니라 인터페이스도 가능하다.
인터페이스라고해서 extends 대신 implement를 사용하지 않는다.
타입 파라미터를 대체할 구체적인 타입
상위타입이거나 하위 또는 구현 클래스만 지정 할 수 있다.
주의할 점 ****
메소드의 중괄호{} 안에서 타입 파라미터 변수로 사용 가능한 것은 상위 타입의 멤버(필드, 메소드)로 제한된다.
하위 타입에만 있는 필드와 메소드는 사용할 수 없다.
public <T extends Number> int compare(T t1, T t2){
double v1 = t1.doubleValue(); //Number 의 doubleValue() 메소드 사용
double v2 = t2.doubleValue(); //Number 의 doubleValue() 메소드 사용
return Double.compare(v1, v2);
}
exam
public class test_BoundedTypeParameter {
static class testUtil {
static <T extends Number> int compare(T t1, T t2) {// 파라미터를 Number 타입으로 제한
double v1 = t1.doubleValue();
double v2 = t2.doubleValue();
return Double.compare(v1, v2);
//Double.compare 메소드는 v1이 v2보다 크면 1, 작으면 -1 같으면 0을 리턴
}
}
public static void main(String[] args) {
//testUtil 클래스의 compare 메소드를 이용 문자열을 사용했기때문에 에러발생
//int result = testUtil.compare("a", "b");
//정상적인 코드
int result1 = testUtil.compare(5, 1);
System.out.println("result1의 결과 = " + result1);
int result2 = testUtil.compare(2.5, 5);
System.out.println("result2의 결과 = " + result2);
int result3 = testUtil.compare(3.3, 3.3);
System.out.println("result3의 결과 = " + result3);
}
}