// Box.java
public class Box {
private Object obj;
public void setObj (Object obj){
this.obj = obj;
}
public Object getObj (){
return obj;
}
}
// BoxExam.java
public class BoxExam {
public static void main(String[] args) {
Box box = new Box();
box.setObj(new Object());
Object obj = box.getObj();
System.out.println(obj);
box.setObj("Hello");
String str = (String)box.getObj();
System.out.println(str);
box.setObj(1);
int value = (int)box.getObj();
System.out.println(value);
}
}
출력값
java.lang.Object@3764951d
Hello
1
같은 동작을 하는 코드를 제네릭을 이용해 표현
// Box.java
public class Box<E> {
private E obj;
public void setObj (E obj){
this.obj = obj;
}
public E getObj (){
return obj;
}
}
// BoxExam.java
public class BoxExam {
public static void main(String[] args) {
Box<Object> box = new Box<>();
box.setObj(new Object());
Object obj = box.getObj();
System.out.println(obj);
Box<String> box2 = new Box<>();
box2.setObj("Hello");
String str = box2.getObj();
System.out.println(str);
Box<Integer> box3 = new Box<>();
box3.setObj(1);
int value = box3.getObj();
System.out.println(value);
}
}
출력값
java.lang.Object@3764951d
Hello
1