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.
==========================
是!看起來不錯。 –
你的問題到底是什麼? –
我的問題是我在想什麼(Casting)是對還是錯。 @Joe C – Erick