Generic

"Java Stuty"

Posted by Chungman on March 25, 2021

Generic 예제

Generic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package Java0325.Lecture14.generic;

import java.util.Random;

class A {
	private Object obj;
	
	public A(Object obj) {
		this.obj =obj;
	}
	
	public void setObject(Object obj) {
		this.obj =obj;
	}
	
	public Object getObj() {
		return this.obj;
	}
	
	public void info() {
		System.out.println("obj : " + obj);
	}
}

class B<T>{
	private T obj;
	
	public B(T obj) {
		this.obj =obj;
	}
	
	public void setObject(T obj) {
		this.obj =obj;
	}
	
	public T getObj() {
		return this.obj;
	}
	
	public void info() {
		System.out.println("obj : " + obj);
	}
}

public class GenericMain {

	public static void main(String[] args) {
		
		B<String> b01 = new B(new String("hello"));
		B<Random> b02 = new B(new Random());
		
		b01.info();
		b02.info();
		
		System.out.println("길이 : " + b01.getObj().length());	// 알아서 명시적형변환을 해줌
		System.out.println("길이 : " + b02.getObj().nextInt());
		
//		b01 = new B<Random>(new Random());		// 예외발생.. b01은 String형
		
		/*
		A a01 = new A(new String("hello"));
		A a02 = new A(new Random());
		
		a01.info();
		a02.info();
		System.out.println("길이 : " + ((String)a01.getObj()).length());
		System.out.println("길이 : " + ((Random)a02.getObj()).nextInt());	
		
		A[] arr = new A[2];
		arr[0] = a01;
		arr[1] = a02;
		*/
	}

}