Question 22
Given
5.  class Building{}
6.  public class Barn extends Building{
7. public static void main(String[] args){
8. Building build1 = new Building();
9. Barn barn1 = new Barn();
10. Barn barn2 = (Barn)build1;
11. Object obj1 = (Object)build1;
12. String str1 = (String)build1;
13. Building build2 = (Building)barn1;
14.  }
15. }
Which is true?
A If line 10 is removed, the compilation succeeds.
B If line 11 is removed, the compilation succeeds.
C If line 12 is removed, the compilation succeeds.
D If line 13 is removed, the compilation succeeds.
E More than one line must be removed for compilation to succeed.12行有问题这个比较明显。
第10行编译可以通过,但是run时却报
Exception in thread "main" java.lang.ClassCastException: Building cannot be cast to Barn
        at Barn.main(Barn.java:10)
我觉得第10行在编译时应该也不能通过,请问这是问什么呢?
为什麽String可以compile时报错,另外自己定义的类就不行?
是因为编译时无法识别Building强制转换到Barn是向下转换吗?
非常感谢。

解决方案 »

  1.   

    这是迟邦定吧late binding select C
      

  2.   

    向下转型是可以的
    实际应用中也是比较常见的
    最常见的就是将Object强转为实际的类型
    e.g User user=(User)session.getAttribute("session_user");
    但是严格来说,在进行向下转换的时候一定进行检查
    User user = null;
    if(object.getClass()==User.class){
     user =(User)object;
    }
      

  3.   

    我来回答你的问题:
    首先,第10句是把父类的对象转换为子类对象,这是不允许的,因为在子类中可能实体变量多于父类中的....只能用父类的对象引用子类的实体。
    其次,类型转换属于运行时异常,这个并不用你自己捕捉,java在运行时其虚拟机会自动抛出异常。