2013-07-09 35 views
0

我在用K &從SCJP書理解從章面向對象的問題九號B.SCJP面向對象發行

問一個問題:

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,因爲Tre e不能被低估到Redwood。我只是有問題來理解這個概念。

+0

'GO2((紅木)新樹(),新的紅木(]'?錯字? – exexzian

回答

2

一個Child類實例可強制轉換爲Parent類的引用,因爲自從Child繼承ParentChild應該支持其已經支持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()不起作用

0

選項A:一個例外是在運行時拋出

因爲go2 ((Redwood) new Tree () , new Redwood (] //運行時異常

Becasue你是鑄造樹對象以紅木對象及其不可能的。 您的Tree類是父類,不能將父類對象向下轉換爲子類對象。

1

如果你傳遞一個樹對象如下那麼它是合法的

Tree t1 = new Redwood(); 

因爲樹可能是紅木或一些樹......這樣你就可以在運行時

2

這條線不是垂頭喪氣在運行時會拋出異常:

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

因爲你鑄造Tree對象Redwood這是不可能

Tree您的類是父類,您不能將父類對象向下轉換爲子類對象。

這是無效的:

(Redwood) new Tree () 

但正好相反。

也就是說這是完全合法:

(Tree) new redwood () 
0

拋出ClassCastException當代碼嘗試將樹倒下來成爲紅木。 所以正確答案是:一個

0

代碼不編譯由於明顯的語法錯誤:在去法]中沒有匹配的[,和' Go方法中沒有匹配的'之後。此外,該代碼缺少兩個}

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