Java 关于铸造对象
我想对了吗? 我在后面用代码解释它// 我从很多网站上读到过,但仍然感到困惑。谢谢你的帮助:) 这是我们所有的 ( 课堂测试 类动物 哺乳类动物 猫科哺乳动物 犬类哺乳动物 ) 这是输出Java 关于铸造对象,java,object,casting,Java,Object,Casting,我想对了吗? 我在后面用代码解释它// 我从很多网站上读到过,但仍然感到困惑。谢谢你的帮助:) 这是我们所有的 ( 课堂测试 类动物 哺乳类动物 猫科哺乳动物 犬类哺乳动物 ) 这是输出 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
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
。编译器确实知道,当且仅当typecast在运行时成功时,(Cat)a
的结果将是Cat
(或null
)。如果typecast没有成功,那么将抛出一个异常(在运行时),并且不会发生对c
的赋值
简而言之,编译器不知道会发生什么,但它知道计算将满足Java的类型安全规则。您基本上是正确的。但这有点错误:
c = (Cat)a; //Compiler see it as Cat as first because we
//(cast) it back.
编译器不知道a
引用了Cat
。它知道它可以引用一个Cat
。编译器确实知道,当且仅当typecast在运行时成功时,(Cat)a
的结果将是Cat
(或null
)。如果typecast没有成功,那么将抛出一个异常(在运行时),并且不会发生对c
的赋值
简而言之,编译器不知道会发生什么,但它知道计算将满足Java的类型安全规则。你的问题是什么?我的问题是我在想什么(强制转换)是对的还是错的@乔:你的问题到底是什么?我的问题是我在想什么(演员)是对的还是错的@乔C