ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JAVA] Generic (제네릭) - WildCard(와일드카드)
    JAVA 2022. 5. 19. 00:12
    반응형

    지난번에 이어 와일드 카드에 대해 공부해 보았습니다.

     

    제네릭에서 와일드 카드란?

     

    코드를 작성할 때, 제네릭으로 입력될 수 있는 타입을 지정할 수 있다는 것을 알게 되었는데 ,

    여기에 와일드카드를 더하면, 이 제네릭타입에 입력 범위를 지정해 줄 수 있다.

     

    방식은 크게 3가지로 나눌 수 있는데,

    1. <?>
    2. <? extends T>
    3. <? super T>

    <?>은 어떤 타입도 입력될 수 있다.

    <? extends T>는 T 타입에 속한 하위 모든 타입들이 입력될 수 있다.

    <? super T>는 T 타입을 포함한 상위의 모든 타입들이 입력될 수 있다.

     

    즉 , extends는 입력타입의 상한선 , super는 입력타입의 하한선이다.

     

    이것이 자바다 교재를 참고한 간단한 예시를 들자면 ,

    public class Course<T> {
    	private String name;
    	//private T[] students;
    	
    	public Course(String name) {
    		this.name = name;
    		//students = (T[]) (new Object[capa]); //타입파라미터로 배열생성하는 방법
    		
    	}
    
    	public String getName() {
    		return name;
    	}
    
    }
    
    public class CourseManage {
    	public static void printCase1(Course<?> course) {
    		System.out.println(course.getName());
    	}
    	public static void printCase2(Course<? super Worker> course) {
    		System.out.println(course.getName());
    	}
    	public static void printCase3(Course<? extends Student> course) {
    		System.out.println(course.getName());
    	}
    	
    }
    
    public class Exam {
    
    	public static void main(String[] args) {
    		Course<Person> personCourse = new Course("일반인과정");
    		Course<Worker> workerCourse = new Course("직장인과정");
    		Course<Student> studentCourse = new Course("학생과정");
    		Course<HighStudent> hiStuCourse = new Course("고등학생과정");
    		
    		CourseManage cm = new CourseManage();
    
    		//case1 : Course<?> : 모든 클래스속성 입력가능
    		cm.printCase1(personCourse);
    		cm.printCase1(workerCourse);
    		cm.printCase1(studentCourse);
    		cm.printCase1(hiStuCourse);
    		
    		//case2 : Course<? super Worker> : Worker와 상위 클래스속성만 입력가능
    		cm.printCase2(workerCourse);
    		cm.printCase2(personCourse);
    		//cm.printCase2(studentCourse);
    		//cm.printCase2(hiStuCourse);
    		
    		//case3 : Course<? extends Student> : Student와 하위 클래스속성만 입력가능
    		//cm.printCase3(personCourse);
    		//cm.printCase3(workerCourse);
    		cm.printCase3(studentCourse);
    		cm.printCase3(hiStuCourse);
    	}
    }

     

    위 예시의 클래스 상속관계

    반응형

    'JAVA' 카테고리의 다른 글

    [SpringBoot] Proxy방식으로 CORS 해결하기  (1) 2024.01.11
    [JAVA] List 컬렉션 - ArrayList  (0) 2022.05.20
    [JAVA] 컬렉션프레임워크  (0) 2022.05.19
    [JAVA] 제네릭 (Generic)  (0) 2022.05.16

    댓글

Designed by Tistory.