2017-02-25 139 views
1

我認爲是對的嗎? 我在code behide中解釋它//關於鑄造對象

我從很多網頁上看過它,但仍然感到困惑。感謝任何幫助:)

這就是我們擁有的一切。

( 類測試

類動物

類哺乳動物擴展動物

類目錄擴展哺乳動物

Dog類擴展哺乳動物

 public static void main(String args[]){ 
     Test test = new Test(); 
     Cat c = new Cat(); // Create object Cat, Now variable c refer to Cat. 

     System.out.println(c.type); 
     c.thisIs(); 
     c.getType(); 
     test.instanceofAllType(c); 
     c.giveMilk(c); 
     test.line(); 

     Animal a = c; //It still refer to Object Cat but compiler see it as Animal. 
     System.out.println(a.type); 
     a.thisIs(); 
     a.getType(); 
     test.instanceofAllType(a); 
        //a.giveMilk(a); Can't use. We don't see method giveMilk() from variable type Animal. 
     test.line(); 

     c = (Cat)a; //Compiler see it as Cat as first because we (cast) it back. 
     System.out.println(c.type); 
     c.thisIs(); 
     c.getType(); 
     test.instanceofAllType(c); 
     c.giveMilk(c); //We can see and use method giveMilk() again. 
     test.line(); 
    } 
} 

這是輸出

Cat 
This is a Cat 
Type =Cat 
Yes ,I'm Animal! 
Yes ,I'm Mammal! 
Yes ,I'm Cat! 
No ,I'm not a Dog 
I'm a cat and i get a milk. 
========================== 
Animal 
This is a Cat 
Type =Cat 
Yes ,I'm Animal! 
Yes ,I'm Mammal! 
Yes ,I'm Cat! 
No ,I'm not a Dog 
========================== 
Cat 
This is a Cat 
Type =Cat 
Yes ,I'm Animal! 
Yes ,I'm Mammal! 
Yes ,I'm Cat! 
No ,I'm not a Dog 
I'm a cat and i get a milk. 
========================== 
+1

是!看起來不錯。 –

+0

你的問題到底是什麼? –

+0

我的問題是我在想什麼(Casting)是對還是錯。 @Joe C – Erick

回答

0

你大多是正確的。然而,這是一個有點不對勁:

 c = (Cat)a; //Compiler see it as Cat as first because we 
        //(cast) it back. 

編譯器不知道aCat。它知道它可能是指Cat。當且僅當類型轉換在運行時成功時,編譯器才知道(Cat) a的結果將是Cat(或null)。如果類型轉換不成功,則會拋出異常(在運行時),並且不會發生對c的分配。

簡而言之,編譯器並不確切知道會發生什麼,但它確實知道計算將滿足Java的類型安全規則。