2017-04-22 106 views
-4

我一直在砸我的头,以了解java中对象类型转换的实际用法,以及为什么它甚至在那里。看下面的例子。对象隐式类型转换的要点是什么?

我的问题是以下面的评论形式。

请不要建议我去某处。我已经做到了。如果你知道,请直接回答我。谢谢。

检查此代码的方法'尖叫'覆盖我没有收到编译时错误。看评论太

Animal aniObj = new Animal(); 
    Animal dogAniObj = new Dog(); 
    Dog dogObj = new Dog(); 

    ArrayList<Animal> animalArrayList = new ArrayList<Animal>(); 

    animalArrayList.add(aniObj); 
    animalArrayList.add(dogAniObj); 
    animalArrayList.add(dogObj);//Here when I am able to add the Dog object there no point in creating dogAniObj above 

    aniObj.scream();//Calls scream of Animal 
    dogAniObj.scream();//Calls scream of Dog 
    dogObj.scream();//Calls scream of Dog. Then why do i need above statement? Why to attain polymorphic behavior when we can directly call scream method with the Dog object when needed? 
+0

欢迎来到SO。你的问题是什么 ? – c0der

+1

相关:http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface –

+0

你在哪里期待编译时错误? – Bubletan

回答

0

这就是Java的给你作为运行时多态性,在运行时是什么对象引用它,该方法的实例将被调用。

认为你是写一些通用的lib /框架,那么所有你想要的用途是Animal类,这是基础,所有其他子类,如Dog, Cat等,那么你可以不是你的成员一样Dog myDog or Cat myCat有声明应该Animal myAnimal使其可以服用所有的动物亚类。

Thast的为什么animalArrayList应该总是采取动物及其变种没有编译错误来。

你永远不知道Animal类可以由你的lib用户扩展来创建许多其他的Animal类。