본문 바로가기
JAVA

Generic

by EUN-JI 2023. 8. 30.

Generic : 객체 생성(new)할때 자료형을 결정

: 아직 명칭이 정해지지 않은 상품(제네릭 상품)

: class를 설계할 때 멤버의 자료형을 결정하지 않고, (new)사용할 때 결정

: 데이터를 하나 멤버변수로 저장하고 있는 Box객체 생성

즉, 멤버변수 1개짜리 Box클래스를 설계

: <>제네릭에 사용할 수 있는 자료형은 참조형만 가능.

: 기본형은 참조형타입으로 감싸줘야 함. = Boolean, Byte, Character, Short, Integer, Float, Double

 

Box<int> b2 = new Box<int>();    //error

Integer num = nue Integer(10);

(축약형)

Integer num = 10;  //자동 new Integer(10)           >>auto boxing 이라함.

int n =num ;   //자동 Integer 객체를 int로 변환     >>auto unboxing이라함. 

//위 처럼 Wrapper클래스를 사용하면 기본형처럼 사용가능

public class Main {
		public static void main(String[] args) {
			
			//Generic [제네릭 - 아직 명칭이 정해지지 않은 상품(제네릭 상품) ]
			//class를 설계할 때 멤버의 자료형을 결정하지 않고..
			//사용할 때 (new 할때) 결정하도록 하는 문법.
			
			//데이터를 하나 멤버변수로 저장하고 있는 Box객체 생성
			// 즉, 멤버변수 1개짜리 Box클래스를 설계
			
			//new 할때 자료형을 결정함.
			Box<String> b= new Box<String>();
			
			b.a= new String("Hello");
			b.a= "Hello";  //자동 new String()   : 축약
			System.out.println(b.a);
			
			//new 할때 정수형을 저장하도록..
			//<>제네릭에 사용할 수 있는 자료형은 참조형만 가능함. ********
			//Box<int> b2=new Box<int>();     // error   ()는 무조건 쓰기 .. 생성자임. 
			
			//기본형을 제네릭의 타입으로 지정하고 싶다면
			//기본형을 참조형타입으로 감싸줘야 함.
			//기본형 8개에 대응된 참조형 자료형들이 존재함
			//이런 클래스들을Weapper 클래스라고 부름
			//[Boolean, Byte ,Character, Short, Integer, Float, Double]
			//Integer num= new Integer(10);
			//축약형
			Integer num = 10;  //자동 new Integer(10)  -->auto boxing 이라고 부름.
			int n = num;  //자동 Integer 객체를 int로 변환   -->auto unboxing 이라 부름.
			System.out.println(n);
			
			//위 처럼 Wrapper 클래스를 사용하면 기본형처럼 사용이 가능함.
			//이를 제네릭에 적용한다.
			Box<Integer> b2 = new Box<Integer>();
			//b2.a= new Integer(100);
			b2.a= 100;  // auto boxing
			System.out.println(b2.a);
			
			Box<Double> b3 = new Box<Double>();
			b3.a =3.14;
			System.out.println(b3.a);
			
			Box<Boolean> b4 = new Box<Boolean>();
			b4.aaa(true);
			boolean k = b4.bbb();
			
			//<>제네릭타입을 여러개 지정할 수 있음.
			Box2<String, Integer> box = new Box2<String, Integer>();
			box.a="Sam";
			box.b=20;
			System.out.println(box.a);
			System.out.println(box.b);
					
}
}
-------------------------------------------------------------------------------------
//new 할때 <>안에 전달되니 자료형으로 멤버의 타입이 결정됨.
public class Box <T>{  // <자료형> Generic 문법
	
	//데이터를 저장하는 멤버변수 1개
	//클래스를 설계할 때는 자료형을 정하지 않도록 ..하고 싶을떄
	T a;
	
	
	//멤버함수의 파라미터나 리턴타입에도 제네릭타입 적용가능
	void aaa(T x){
		this.a= x;
	}
	
	T bbb() {
		return this.a;
	}
}
------------------------------------------------------------------------------------
//<>제네릭타입을 여러개 지정할 수 있음.

public class Box2<T,G> {
	T a;
	G b;
}

'JAVA' 카테고리의 다른 글

Thread  (0) 2023.08.30
Collection API: List, Set, Map  (2) 2023.08.30
예외처리: try-catch-finally, throws, throw  (0) 2023.07.15
Object 클래스: 모든 클래스의 (최상위)  (0) 2023.07.15
인터페이스(Interface)  (0) 2023.07.15