The following class can accept and return any type of object.
It cannot, however, accept primitive types (그러나 기본 유형을 허용할 수는 없습니다.)
public class Box {
private Object object;
public void set (Object object){
this.object = object;
}
public Object get(){
return object;
}
}
If we want to create a class that can accept and return any type, we need to replace references in our code to Object with a generic type variable T.
public class Box<T> {
private T t;
public void set (T t){
this.t = t;
}
public T get(){
return t;
}
}
In a generic class, the <> following the class name is the type parameter.
This is how you would instaniate an object of Box class that can accept and return any type:
* following 다음 instaniate 인스턴스화 하다.
* This is how you would instaniate 이것이 당신이 인스턴스화하는 방법입니다
* This is how you would 이것이 당신이 ~ 하는 입니다
Box<Integer> box1 = new Box<Integer>();
Box<Integer> box2 = new Box<>();'Java - English ver' 카테고리의 다른 글
| Using buffered streams (0) | 2024.11.12 |
|---|---|
| Type inference in generic calsses (0) | 2024.11.11 |
| Using bounded type parameters in generic methods (3) | 2024.11.08 |
| Type Inference in Generic Methods (3) | 2024.11.07 |
| Writing generic methods (0) | 2024.11.06 |