JAVA 10강_1_제네릭(generic)_예시2

열라뽕따히·2024년 2월 25일
0

JAVA

목록 보기
62/79

StringType의 클래스 생성



=============================코드=============================

public class StringType {
	
	String[] str;
	String var;
	
	void setStr(String[] str) {
		
		this.str = str;
		
	}
	
	void setVar(String var) {
		
		this.var = var;
		
	}
	
	void output() {
		
		for(String s : str) {
			System.out.println("str 배열 요소 >>> " + s);
		}
		System.out.println("var >>> " + var);
	}

}



IntegerType 클래스 생성



=============================코드=============================

public class IntegerType {
	
	Integer[] iarr;
	Integer ivar;
	
	void setStr(Integer[] iarr) {
		
		this.iarr = iarr;
		
	}
	
	void setVar(Integer ivar) {
		
		this.ivar = ivar;
		
	}
	
	void output() {
		
		for(Integer s : iarr) {
			System.out.println("iarr 배열 요소 >>> " + s);
		}
		System.out.println("ivar >>> " + ivar);
	}

}




메인메서드로 출력할 Type_04 클래스 생성




=============================코드=============================

public static void main(String[] args) {
		
		// StringType 클래스 객체 생성
		StringType st = new StringType();
		
		String[] str = {"홍길동", "세종대왕", "유관순"};
		String var = "김유신";
		
		st.setStr(str);
		st.setVar(var);
		
		st.output();
		
		System.out.println();
		
		// IntegerType 클래스 객체 생성
		IntegerType it = new IntegerType();
		
		Integer[] iarr = {10, 20, 30, 40, 50};
		Integer ivar = 157;
		
		it.setStr(iarr);
		it.setVar(ivar);
		
		it.output();

	}

=============================실행=============================





이번엔 제네릭을 활용하여 출력해보자!
Generic 클래스 생성




=============================코드=============================

public class Generic<T> {
	
	T[] arr;
	T var;
	
	void setArr(T[] arr) {
		this.arr = arr;
	}
	
	void setVar(T var) {
		this.var = var;
	}
	
	void output() {
		
		for(T t : arr) {
			System.out.println("arr 배열 요소 >>> " + t);
		}
		System.out.println("var >>> " + var);
		
	}

}



메인메서드로 출력할 Generic_05 클래스 생성



=============================코드=============================

public static void main(String[] args) {
		
		// String 타입의 클래스 객체 생성
		Generic<String> st = new Generic<String>();
		
		String[] str = {"홍길동", "세종대왕", "유관순"};
		String var = "김유신";
		
		st.setArr(str);
		st.setVar(var);
		
		st.output();
		
		System.out.println();
		
		// IntegerType 클래스 객체 생성
		IntegerType it = new IntegerType();
		
		Integer[] iarr = {10, 20, 30, 40, 50};
		Integer ivar = 157;
		
		it.setStr(iarr);
		it.setVar(ivar);
		
		it.output();

	}

=============================실행=============================

0개의 댓글