gpt4 book ai didi

java - SCJP 面向对象问题

转载 作者:行者123 更新时间:2023-12-01 07:31:04 28 4
gpt4 key购买 nike

我在理解 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。我只是无法理解这个概念。

最佳答案

>

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;
}

关于java - SCJP 面向对象问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17544166/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com