전공 과목 이수2👨‍💻/JAVA(공)

Java | 제네릭(generic)

천숭이 2021. 4. 28. 01:10

같은 기능을 하지만 자료형에 따라 중복된 프로그램을 작성해야 한다.

제네릭은 자료형을 <매개변수>로 가질 수 있다.

 

제네릭클래스 = 범용클래스, 포괄클래스

 

package soobin;

class StudentInfo{
	public int grade;
	StudentInfo(int grade){this.grade=grade;}
}
class StudentPerson{
	public StudentInfo info;
	StudentPerson(StudentInfo info){this.info = info;}
}
class EmployeeInfo{
	public int rank;
	EmployeeInfo(int rank){this.rank = rank;}
}
class EmployeePerson{
	public EmployeeInfo info;
	EmployeePerson(EmployeeInfo info){this.info = info;}
}

public class GenericDemo {
	public static void main(String[] args) {
		StudentInfo si =new StudentInfo(2);
		StudentPerson sp=new StudentPerson(si);
		System.out.println(sp.info.grade);  //2
		EmployeeInfo ei = new EmployeeInfo(1);
		EmployeePerson ep = new EmployeePerson(ei)	;
		System.out.println(ep.info.rank); //1
	}
}

new StudentInfo 클래스의 객체 si를 만드는데 매개로 2를 주워 생성자클래로 들어간다. 따라서 si의 grade는 2.

만들어진 si는 생성된 StudentPerson의 매개로 들어간다. 따라서 sp의 info는 2가  저장된다(출력으로확인)

ei와 ep도 똑같은형태

 

여기서 StudentPerson클래스와 EmployeePerson의 기능이 같다

= 중복이 발생했다. 따라서 이 둘의 공통적인 클래스를 만들어서 중복을 제거해야한다.

중복을 제거하면 좋은점 

1. 코드의 길이가 줄어든다

2. 유지보수하기가 편하다

 

제네릭의 매개로 기본데이터타입을 사용하려면 레퍼클래스를 사용해야한다.

*래퍼클래스란 기본데이터타입을 객체로 포장하는 형태. int 를 Integer로 작성하면된다. (각각의 기본데이터 타입마다 래퍼클래스가 존재)

package soobin;

class StudentInfo{
	public int grade;
	StudentInfo(int grade){this.grade=grade;}
}

class EmployeeInfo{
	public int rank;
	EmployeeInfo(int rank){this.rank = rank;}
}
class Person<T,S>{
	public T info;
	public S id;
	Person(T info, S id){
		this.info = info;
		this.id = id;
	}
}

public class GenericDemo {
	public static void main(String[] args) {
	    // Integer id =new Integer(1)
		
		// 기본데이터타입을 래핑하기
		Person<EmployeeInfo, Integer> p1 = new Person<EmployeeInfo, Integer>(new EmployeeInfo(1),1);
		System.out.println(p1.id.intValue());
		// intValue : 래퍼클래스가 담고 있는 원래의 숫자를 기본 데이터타입으로 돌려주는 함수
	}
}

package soobin;

class StudentInfo{
	public int grade;
	StudentInfo(int grade){this.grade=grade;}
}

class EmployeeInfo{
	public int rank;
	EmployeeInfo(int rank){this.rank = rank;}
}
class Person<T,S>{
	public T info;
	public S id;
	Person(T info, S id){
		this.info = info;
		this.id = id;
	}
	public <U> void printInfo (U info) { // u로 지정된 데이터타입에 따라 info의 데이터타입도 결정
		System.out.println(info);
	}
}

public class GenericDemo {
	public static void main(String[] args) {
		EmployeeInfo e = new EmployeeInfo(1);
	    //Integer id =new Integer(1);
		
		// 기본데이터타입을 래핑하기
		Person<EmployeeInfo, Integer> p1 = new Person<EmployeeInfo, Integer>(new EmployeeInfo(1),1);
		System.out.println(p1.id.intValue());
		// intValue : 래퍼클래스가 담고 있는 원래의 숫자를 기본 데이터타입으로 돌려주는 함수
		
		p1.printInfo(e);
		// e를 EmployeeInfo로 지정 (p1.<EmployeeInfo>printInfo(e);로 작성가능)
	}
}