티스토리 뷰




Why use Generics in Java? 


- Class를 정의할 때는 datatype을 정하지 않고, 인스턴스를 생성할 때 datatype을 지정하는 것이 Java Generic 이다.

- Java Generics은 기본datatype 에서는 사용하지 않고 reference datatype(e.g. Arrays, Class, Interface etc) 에서만 사용가능하다.

- Generic은 compile time error를 발견하게 도와준다. -> 프로그램상에서 런타임에러는 심각한 문제를 초래 할 수 있기 때문에 컴파일에러가 나도록 유도해야한다. 




*runtime error compile error 런타임에러와 컴파일 에러란? 


compile 이란?

인간이 이해하기 쉽게 하려고 만든 소스코드를 다시 기계어로 변환하려는 작업 

compile error 란? 

코드에 에러가 있을때 경고를 띄워주는 에러 타입 e.g. Syntax error


runtime 이란?

컴퓨터 프로그램이 실행되고 있는 동안의 동작 즉, 실행시간

runtime error 란? 

런타임에러는 실제로 코드가 실행되고 있을때 발생한다. 프로그램이 충돌을 일으킬 수 있기에 문제를 추적하기에도 까다롭다. e.g running out of memory






Generic class example code


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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>{
    public T info;
    Person(T info){ this.info = info; }
}
public class GenericDemo {
    public static void main(String[] args) {
        Person<EmployeeInfo> p1 = new Person<EmployeeInfo>(new EmployeeInfo(1));
        EmployeeInfo ei1 = p1.info;
        System.out.println(ei1.rank); // 성공
         
        Person<String> p2 = new Person<String>("부장");
        String ei2 = p2.info;
        System.out.println(ei2.rank); // 컴파일 실패
    }
}
cs




Generic method example code


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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){
        System.out.println(info);
    }
}
public class GenericDemo {
    public static void main(String[] args) {
        EmployeeInfo e = new EmployeeInfo(1);
        Integer i = new Integer(10);
        Person<EmployeeInfo, Integer> p1 = new Person<EmployeeInfo, Integer>(e, i);
        p1.<EmployeeInfo>printInfo(e);
        p1.printInfo(e);
    }
}
cs







Reference

https://opentutorials.org/course/1223/6237

'JAVA' 카테고리의 다른 글

wrapper class in java  (0) 2019.01.07
String methods in Java  (0) 2019.01.07
static in Java  (0) 2019.01.05
Overloading in Java with simple example  (0) 2019.01.04
Overriding in Java with an simple code  (0) 2019.01.04