Frog is cry
제네릭 본문
package 제네릭;
public class Generic<T> {
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
package 제네릭;
public class Generic_Test {
public static void main(String[] args) {
// 제네릭에서는 꼭 Wrapper클래스를 사용해야함
Generic<String> g = new Generic<>();
Generic<Integer> g2 = new Generic<>();
g.setData("안녕");
g2.setData(new Integer(10));
System.out.println(g.getData());
System.out.println(g2.getData());
System.out.println(Generic_Test2.function(3.9F));
System.out.println(Generic_Test2.function(10));
System.out.println(Generic_Test2.function('A'));
System.out.println(Generic_Test2.function("한동석"));
}
}
package 제네릭;
public class Generic_Test2 {
public static <T> T function(T data) {
T result;
if(data instanceof Integer) {
result = (T)"정수";
}else if (data instanceof Double || data instanceof Float) {
result = (T) "실수";
}else if(data instanceof Character) {
result = (T)"문자";
}else if(data instanceof String) {
result = (T)"문자열";
}else{
result = null;
}
return result;
}
}
package 제네릭;
public interface Ginter<N1, N2> {
abstract N1 add(N1 data1, N1 data2);
N1 sub(N1 data1, N2 data2);
N2 mul(N2 data1, N2 data2);
}
package 제네릭;
public class Calc implements Ginter<Double, Integer>{
@Override
public Double add(Double data1, Double data2) {
return data1 + data2;
}
@Override
public Double sub(Double data1, Integer data2) {
return data1 - data2;
}
@Override
public Integer mul(Integer data1, Integer data2) {
return data1 * data2;
}
public static void main(String[] args) {
Calc c = new Calc();
System.out.printf("%.2f\n", c.add(5.9, 12.23));
System.out.printf("%.2f\n", c.sub(5.9, 12));
System.out.printf("%.2f\n", c.mul(5,12));
}
}
'JAVA > 복습' 카테고리의 다른 글
컬렉션 프레임워크(Array List) (0) | 2020.07.29 |
---|---|
Set (0) | 2020.07.29 |
오브젝트 (0) | 2020.07.29 |
Wrapper 클래스 (0) | 2020.07.29 |
예외처리(엘레베이터 예제) (0) | 2020.07.29 |
Comments