제너릭 타입도 다른 타입과 마찬가지로 부모클래스가 될 수 있다.


특징

자식 제너릭타입에 타입 파라미터를 추가 가능!



Product라는 제너릭타입이 있다.


1
2
3
public class Product<T, M> {
    //생략
}
cs



Product를 상속받은 ChildProduct는 추가로 타입파라미터를 가질수 있다.

1
2
3
4
public class ChildProduct<T, M, C> extends Product<T, M> {
            //제너릭 타입을 상속받을 때 자식은 추가 타입 파라미터를 가질수 있다.
    //생략..
}
cs


?를 보통 와일드카드라고 부른다.


제너릭타입에서는 구체적인 타입을 명시하는 대신 와일드카드를 이용할 수 있다.


제너릭 타입<?> : Unbounded WildCards  

제너릭 타입<? extends 상위클래스> : Upper Bounded WildCards - 상위타입이나 하위타입만

제너릭 타입<? super 하위클래스> : Lower Bounded WildCards - 하위타입이나 상위타입만


수강생을 예를 들어서 살펴보면

수강생들은 다음과 같은 상속관계를 가지고 있다. 



코드를 통해 와이드카드 타입 매개변수를 살펴보자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Arrays;
 
public class WildCardExample {
    public static void registerCourse(Course<?> course) { 
                                    //모든 수강생이 들을수 있는 과정
        System.out.println(course.getName() + "수강생: " + Arrays.toString(course.getStudents()));
    }
 
    public static void registerCourseStudents(Course<extends Student> course) { 
                                                //학생들만 들을 수 있는 과정(Student, HighStudent)
        System.out.println(course.getName() + "수강생: " + Arrays.toString(course.getStudents()));
    }
    
    public static void registerCourseWorker(Course<super Worker> course) { 
                                            //직장인과 일반인 들을 수 있는 과정(Worker, Person)
        System.out.println(course.getName() + "수강생: " + Arrays.toString(course.getStudents()));
    }
}
cs


'Java' 카테고리의 다른 글

[람다식] 람다식 기본  (0) 2017.02.24
[제너릭]제너릭 타입의 상속  (0) 2017.02.17
[제너릭]제너릭 메소드  (0) 2017.02.16
[제너릭] 제너릭과 비제너릭 비교  (0) 2017.02.15
Thread 상속으로 thread 생성  (0) 2017.01.27

제너릭 메소드


제너릭 메소드란?


매개타입과 리턴타입으로 타입 파리미터를 갖는 메소드



제너릭 메소드 호출 방법


이 제너릭 메소드를 호출하는 방법은 구체적 타입을 명시적으로 지정하는 방법과

컴파일러과 매개값을 보고 구체적인 타입을 추정하게 하는 방법이 있다.


이 방법들을 실제 코드를 통해 살펴보자.



제너릭 메서드 구현


1
2
3
4
5
6
7
8
public class Util {
    public static <T> Box<T> boxing(T t) {  //제너릭 메소드는 <T> 매개변수 타입과
                                            //Box<T> 리턴타입으로 타입 파라미터를 갖는 메서드
        Box<T> box = new Box<T>();
        box.set(t);
        return box;
    }
}
cs



제너릭 메서드 호출


1
2
3
4
5
6
7
8
9
public class BoxingMethodExample {
    public static void main(String[] args) {
        Box<Integer> box1 = Util.<Integer>boxing(100); //구체적 타입을 명시하여 호출
        int intValue = box1.get();
        
        Box<String> box2 = Util.boxing("북스터디"); //컴파일러가 추정하게 하여 호출
        String name = box2.get();
    }
}
cs


+ Recent posts