본문 바로가기
Java/Java

자바 제네릭(Generic)

by code2772 2022. 10. 12.

[ 목차 ]

    728x90
    반응형
    1. 제네릭(Generic)
    
    클래스나 메소드에서 사용할 데이터의 타입을 컴파일시에 미리 지정하는 방법
    
    제네릭을 사용하는 이유
    - 다양한 타입의 객체의 재사용을 높일 수 있음
    - 클래스에서 사용할 타입을 외부에서 사용
    - 반복적인 코드, 불필요한 코드를 사용하지 않도록 함
    - 강제적인 형변환을 발생시키지 않음
    public class Generic1 {
        public static void main(String[] args) {
           // Box2<String> box1 = new Box2<String>();
           // Box2<String> box1 = new Box2<>();
              Box2<String> box1 = new Box2();
              box1.setT("안녕하세요");
            System.out.println(box1.getT());
            String str = box1.getT();// 형변환이 필요없다. -> 제네릭의 장점 : 자동변환
    
            Box2<Integer> box2= new Box2<>();
            box2.setT(100);
            System.out.println(box2.getT());
            Integer i = box2.getT();
    
            Apple apple = new Apple("사과",1000,"red","충주","소과");
            Box2<Apple> box3 = new Box2<>();
            box3.setT(apple);
    
            Apple apple2 = box3.getT();
            System.out.println(apple2);
    
    
        }
    }
    

     

    ✔ Object 클래스
    - 자바의 모든 클래스의 최상위 조상 클래스
    - 모든 타입은 Object 클래스 객체화 시킬 수 있음
    - 기본 데이터 타입을 객체화 시킨 래퍼타입으로 대입 받을 수 있음
    
    
    public class Box2<T> {
        private T num1;
        private T num2;
        public T sum(T num1, T num2){
        return num1+ num2
       }
    }
    ---------------------------------------------------
    Box2<Integer> box1 = new Box2();  -----> T 에 있던것이 Integer해당 형으로 바뀐다.
    box1.sum(10,20);
    Box2<Double> box2 = new Box2();// 원하는 형으로 자동 변환해주는 것을 제네릭이라고 한다.
    box2.sum(10.2,20.5);
    ------------>
    public class Box2<Integer> {
        private Integer num1;
        private Integer num2;
        public Integer sum(Integer num1, Integer num2){
        return num1+ num2
       }
    
    <T> : Type
    <E> : Element
    <K> : Key
    <V> : Value
    <N> : Number
    

     

    public class GenericTest<K, V> {
        private K first;
        private V second;
    
    
        public void set(K first, V second){
            this.first = first;
            this.second = second;
        }
    
        public K getFirst() {
            return first;
        }
    
        public void setFirst(K first) {
            this.first = first;
        }
    
        public V getSecond() {
            return second;
        }
    
        public void setSecond(V second) {
            this.second = second;
        }
    }
    

     

    public class Generic2 {
        public static void main(String[] args) {
            GenericTest<String,Integer> generic2 = new GenericTest<>();
            generic2.set("1",100);
    
            System.out.println("first : "+generic2.getFirst());
            System.out.println("second : "+generic2.getSecond());
    
            System.out.println("K Type : "+ generic2.getFirst().getClass().getName());
            System.out.println("V Type : "+ generic2.getSecond().getClass().getName());
        }
    }
    

     

    반응형

    'Java > Java' 카테고리의 다른 글

    JAVA (TCP/IP, 서버 클라이언트)  (0) 2022.10.20
    JAVA 네트워크  (0) 2022.10.20
    자바 스레드  (0) 2022.10.07
    자바 영어단어장  (0) 2022.10.07
    자바 File 다루기  (1) 2022.10.07