Given the code fragment:
interface Contract {
}
class Super implements Contract {
}
class Sub extends Super {
}
public class Ref {
public static void main(String[] args) {
List objs = new ArrayList();
Contract c1 = new Super();
Contract c2 = new Sub(); // line n1
Super s1 = new Sub();
objs.add(c1);
objs.add(c2);
objs.add(s1); // line n2
for (Object itm : objs) {
System.out.println(itm.getClass().getName());
}
}
}
What is the result?
A.
Super
Sub
Sub
Sub
Sub
B.
Contract
Contract
Super
Contract
Super
C. Compilation fails at line n1
D. Compilation fails at line n2
题解
这题的 ArrayList 对象并没有使用到泛型,因此 ArrayList 对象可以存入任意的 Object 对象。
对象的 getClass 方法会回传对象实体所属的类别。
