[英]About Casting Object
我認為對嗎? 我在代碼中解釋它behide //
我從許多網站上讀過這篇文章,但仍然感到困惑。 感謝任何幫助:)
這就是我們所擁有的一切。
(課堂測試
類動物
哺乳動物類延伸動物
Cat類擴展了哺乳動物
class 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.
==========================
你大多是正確的。 但是這有點不對勁:
c = (Cat)a; //Compiler see it as Cat as first because we
//(cast) it back.
編譯器不知道a
指的是Cat
。 它知道,它可以指Cat
。 當且僅當類型轉換在運行時成功時,編譯器確實知道(Cat) a
的結果將是Cat
(或null
)。 如果類型轉換沒有成功,那么將拋出異常(在運行時)並且不會發生對c
的賦值。
簡而言之,編譯器並不確切知道會發生什么,但它確實知道計算將滿足Java的類型安全規則。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.