关于Casting Object

时间:2017-02-25 11:31:07

标签: java object casting

我认为对吗? 我在代码behide //

中解释它

我从许多网站上读过这篇文章,但仍然感到困惑。感谢任何帮助:)

这就是我们所拥有的一切。

( class Test

类动物

类哺乳动物扩展动物

类Cat扩展了哺乳动物

类狗延伸哺乳动物

        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)

你大多是正确的。但是这有点不对劲:

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

编译器不知道a是指Cat。它知道可以引用Cat。当且仅当类型转换在运行时成功时,编译器确实知道(Cat) a的结果将是Cat(或null)。如果类型转换没有成功,那么将抛出异常(在运行时)并且c的赋值不会发生。

简而言之,编译器并不确切知道会发生什么,但它确实知道计算将满足Java的类型安全规则。