본문 바로가기

백엔드개발자 준비하기

[백엔드개발자 준비하기] 제네릭

스태틱 안에는 스태틱만 사용가능
멤버 메소드는 주소가 생성되어 있어야 사용가능
<?> : 와일드카드
-와일드카드로 객체를 만들면 자료형이 모호해짐
-그냥 오브젝트 자료형으로 바뀐거라고 생각하면 됨

? 와일드카드 제약
? extends 자료형 : 앞으로 해당 메소드가 리턴될때는 해당 자료형을 상속받은 자료형만 리턴가능
ex) person -> Student Teacher : 가능 Car : 불가능
? super 자료형 : 자료형을 기준으로 상위객체만 가능함
ex) Student -> Sstudent Person : 가능 Teacher : 불가능

 

[예시1]

 

[TestData]

public class TestData<T, E> {

	private T data1;
	private E data2;	// Wrapper Class(래퍼 클래스)
	
	public TestData(T data1, E data2) {
		this.data1 = data1;
		this.data2 = data2;
	}

	@Override
	public String toString() {
		return "TestData [data1=" + data1 + ", data2=" + data2 + "]";
	}
}

[Main]

public class Main {

	public static void main(String[] args) {
		
		TestData<?, ?> td = new TestData<String, Integer>("김준일", 30);
		TestData<?, ?> td2 = new TestData<String, Double>("junil", 100.05);
		
		System.out.println(td);
		System.out.println(td2);
		
		CMRespDto<?> cm = new CMRespDto<>(200, "성공", td);
		
		System.out.println(cm);
	}
}

 

[예시2]

 

[CMRespDto]

public class CMRespDto<T> {
	
	private int code;
	private String message;
	private T data;
	
	public CMRespDto(int code, String message, T data) {
		super();
		this.code = code;
		this.message = message;
		this.data = data;
	}

	@Override
	public String toString() {
		return "CMRespDto [code=" + code + ", message=" + message + ", data=" + data + "]";
	}
	
	
}

[Main]

public class Main2 {
	public CMRespDto<?> reponse(CMRespDto<?> cmRespDto){
		System.out.println("[응답데이터]");
		System.out.println(cmRespDto);
		return cmRespDto;
	}
	
	public static void main(String[] args) {
		Main2 main = new Main2();
		
		CMRespDto<String> hello = new CMRespDto<String>(200, "성공", "안녕하세요");
		
		CMRespDto<Integer> score = new CMRespDto<Integer>(200, "성공", 85);
		System.out.println("hello");
		System.out.println(main.reponse(hello));
		
		System.out.println("score");
		System.out.println(main.reponse(score));
		// 안녕하세요.
	}
}