0

我在理解 K&B 的 SCJP 书中的面向对象章节中的第 9 题时遇到问题。

问题:

public class Redwood extends Tree { 

public static void main (String [] args) { 
new Redwood ( ) . go ( ) ; 

} 

void go ( ) { 

go2 (new Tree ( ) , new Redwood ( ) ) ; 

go2 ( (Redwood) new Tree ( ) , new Redwood ( ] 

}  

void go2 (Tree tl, Redwood rl) { 

Redwood r2 = (Redwood) tl; 

Tree t2 = (Tree)rl; 
}
}


class Tree { } 

选项:

What is the result? (Choose all that apply.) 

A. An exception is thrown at runtime 

B. The code compiles and runs with no output 

C. Compilation fails with an error at line 8 

D. Compilation fails with an error at line 9 

E. Compilation fails with an error at line 12 

F. Compilation fails with an error at line 13 

书中给出的答案是 A,因为 Tree 不能落入 Redwood。我只是在理解这个概念时遇到了问题。

4

7 回答 7

3

>

class Tree{
   // super class
}

public class Redwood extends Tree{
   //child class
   public static void main (String [] args) { 
   new Redwood ( ) . go ( ) ; // Calling method go()
    } 

    void go ( ) { 

   go2 (new Tree ( ) , new Redwood ( ) ) ; 

   go2 ( (Redwood) new Tree ( ) , new Redwood ( )); // Problem is Here

   /*
   (Redwood)new Tree(),------>by this line Tree IS-A Redwood Which wrong


   According to Question
     Redwood IS-A Tree So relationship is
     (Tree) new Redwood();


   */

  } 

  void go2 (Tree tl, Redwood rl) { 

  Redwood r2 = (Redwood) tl; 

  Tree t2 = (Tree)rl; 
}
于 2013-07-09T09:40:33.087 回答
2

此行将在运行时抛出异常:

go2 ( (Redwood) new Tree ( ) , new Redwood ( ));

因为您正在投射一个不可能的Tree对象Redwood

您的Tree类是父类,您不能将父类对象向下转换为子类对象。

这是无效的:

(Redwood) new Tree ( )

但反之亦然。

这是完全有效的:

(Tree) new redwood ( )
于 2013-07-09T09:12:28.150 回答
1

如果您按以下方式传递树对象,则它是合法的

Tree t1 = new Redwood ();

因为树可以是红木或某棵树......所以你不能在运行时沮丧

于 2013-07-09T09:11:59.883 回答
1

Child实例可以转换为Parent类引用,因为由于Child继承ParentChild 应该支持所有Parent已经支持的行为。

例子

class Parent {

   public void getA() {
        return 1;
   }

}

class Child extends Parent {


   public void getB() {
       return 1;
   }

}

现在让我们考虑 2 个对象

Child c = new Child();
Parent p = new Parent();

现在如果你这样做

Parent p2 = (Parent) c;

这是有效的,因为当您调用 时p2.getA(),它会起作用,因为getA()方法已经被哪个实例继承cChild

现在如果你这样做

Child c2 = (Parent) p;

这将不起作用,因为类型c2is Child,并且调用c2.getB()有效。但是由于实例p是 type Parent,它没有实现getB()(这是子类在继承中添加的新方法)。

简单来说,继承是一种IS A关系

回到你的问题

A Redwood IS A Tree如此Tree t = (Tree) (new Redwood());有效。这意味着Redwood可以将实例强制转换为Tree

但是 aTree 不是 A Reedwood总是(它可以是任何东西).. 所以Redwood r = (Redwood) new Tree()不起作用

于 2013-07-09T09:20:53.463 回答
0

由于明显的语法错误,该代码无法编译:]go 方法中的 in 没有匹配['go 方法的 after 也没有匹配'。此外,该代码缺少两个}.

于 2013-07-09T09:28:54.293 回答
0

选项 A:运行时抛出异常

因为go2 ( (Redwood) new Tree ( ) , new Redwood ( ]//运行时异常

因为您将 Tree 对象转换为 Redwood 对象,这是不可能的。您的 Tree 类是父类,您不能将父类对象向下转换为子类对象。

于 2013-07-09T09:10:50.297 回答
0

当代码尝试将 Tree 向下转换为 Redwood 时,将引发 ClassCastException。所以正确答案是:A

于 2013-07-09T09:26:52.953 回答