首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >面向对象问题

面向对象问题
EN

Stack Overflow用户
提问于 2013-07-09 09:04:47
回答 6查看 296关注 0票数 0

我很难理解K&B的SCJP书中第9章的对象定位问题。

问题:

代码语言:javascript
复制
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 { } 

选项:

代码语言:javascript
复制
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,因为树不能被降到红杉树下。我只是很难理解这个概念。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2013-07-09 09:20:53

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

示例

代码语言:javascript
复制
class Parent {

   public void getA() {
        return 1;
   }

}

class Child extends Parent {


   public void getB() {
       return 1;
   }

}

现在让我们考虑两个对象

代码语言:javascript
复制
Child c = new Child();
Parent p = new Parent();

如果你这么做了

代码语言:javascript
复制
Parent p2 = (Parent) c;

这是有效的,因为当您调用p2.getA()时,它将工作,因为getA()方法已经是继承的cChild的实例。

如果你这么做了

代码语言:javascript
复制
Child c2 = (Parent) p;

这将无法工作,因为c2的类型是Child,而调用c2.getB()是有效的。但是由于实例pParent类型的,所以它没有getB()的实现(这是通过子类在继承中添加的新方法)。

简单地说,继承是一个IS A关系

回到你的问题上

Redwood 是一个 Tree,所以Tree t = (Tree) (new Redwood());可以工作。这意味着可以将Redwood实例转换为Tree

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

票数 1
EN

Stack Overflow用户

发布于 2013-07-09 09:40:33

代码语言:javascript
复制
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; 
}
票数 3
EN

Stack Overflow用户

发布于 2013-07-09 09:11:59

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

代码语言:javascript
复制
Tree t1 = new Redwood ();

因为树可以是红木或者是一棵树..。所以你不能在运行时

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17544166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档