我很难理解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,因为树不能被降到红杉树下。我只是很难理解这个概念。
发布于 2013-07-09 09:20:53
Child类实例可以转换为Parent类引用,因为Child继承了Parent,Child应该支持Parent已经支持的所有行为。
示例
class Parent {
public void getA() {
return 1;
}
}
class Child extends Parent {
public void getB() {
return 1;
}
}现在让我们考虑两个对象
Child c = new Child();
Parent p = new Parent();如果你这么做了
Parent p2 = (Parent) c;这是有效的,因为当您调用p2.getA()时,它将工作,因为getA()方法已经是继承的,c是Child的实例。
如果你这么做了
Child c2 = (Parent) p;这将无法工作,因为c2的类型是Child,而调用c2.getB()是有效的。但是由于实例p是Parent类型的,所以它没有getB()的实现(这是通过子类在继承中添加的新方法)。
简单地说,继承是一个IS A关系
回到你的问题上
Redwood 是一个 Tree,所以Tree t = (Tree) (new Redwood());可以工作。这意味着可以将Redwood实例转换为Tree。
但是Tree 并不总是 Reedwood (它可以是任何东西)。所以Redwood r = (Redwood) new Tree()不起作用
发布于 2013-07-09 09:40:33
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-09 09:11:59
如果按如下方式传递树对象,则它是合法的。
Tree t1 = new Redwood ();因为树可以是红木或者是一棵树..。所以你不能在运行时
https://stackoverflow.com/questions/17544166
复制相似问题