1. 아래가 에러나는 이유를 설명하시오.
class Plastic {}
class Toy extends Plastic {}
class Car extends Toy {}
class Robot extends Toy {}
class Box<T> {
private T ob;
public void set(T o) { ob = o; }
public T get() { return ob; }
public static void inBox(Box<? super Toy> box, Toy n) {
box.set(n);
Toy myToy = box.get();
}
}
- The type of "Box" is "Toy" or one of parent classes of "Toy".
- The "myToy" has memory number of its parent "Box" already, but the "Box" from box.get() is not the parent instance of "myToy".
- So auto casting doesnt occur from box.get() to "myToy".
- So javac is not able to compile this code.
2.아래의 소스코드 중에 System.out.println(zBox.get().get().get()); 부분을 설명하시오.
class Box<T> {
private T ob;
public void set(T o) {
ob = o;
}
public T get() {
return ob;
}
}
public class BoxInBox {
public static void main(String[] args) {
Box<String> sBox = new Box<>();
sBox.set("I am so happy.");
Box<Box<String>> wBox = new Box<>();
wBox.set(sBox);
Box<Box<Box<String>>> zBox = new Box<>();
zBox.set(wBox);
System.out.println(zBox.get().get().get());
}
}
3. 와일드 카드와 상한 제한, 하한 제한에 대하여 설명하시오.
Generic<? extends T> generic
: The type is not allowed to be parent class of T. But, (generic instanceof T) = true .
Generic<? super T> generic
: The type is not allowed to be child class of T. But, (t instanceof Generic) = true .
4. 아래와 같이 메소드 오버로딩이 되지 않는 이유는?
public static void outBox(Box<? extends Toy> box) {...}
public static void outBox(Box<? extends Robot> box) {...}
- Generic is defined during compiling.
- So defined method doesnt care the generic anymore.
- The two methods are already same without generic keywords.
- So javac is not able to compile this code.