Java 对象隐式类型转换的意义是什么?

Java 对象隐式类型转换的意义是什么?,java,object-oriented-analysis,typecasting-operator,Java,Object Oriented Analysis,Typecasting Operator,我一直在绞尽脑汁去理解对象类型转换在java中的真正用途,以及它为什么会存在。见下面的例子 我的问题以下面的评论形式提出 请不要建议我去什么地方。我已经做到了。如果你知道,请直接回答我。谢谢 在重写方法“尖叫”的情况下检查此代码我没有收到编译时错误。也要看评论 Animal aniObj = new Animal(); Animal dogAniObj = new Dog(); Dog dogObj = new Dog(); ArrayList<Anima

我一直在绞尽脑汁去理解对象类型转换在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?
aniObj=新动物();
动物dogAniObj=新狗();
Dog dogObj=新狗();
ArrayList animalArrayList=新ArrayList();
animalArrayList.add(aniObj);
animalArrayList.add(dogAniObj);
animalArrayList.add(dogObj)//在这里,当我能够添加Dog对象时,在上面创建dogAniObj就没有意义了
aniObj.尖叫()//动物的叫声
dogAniObj.尖叫()//狗叫
尖叫声//狗的尖叫声。那我为什么需要上面的陈述呢?当我们可以在需要时直接用Dog对象调用cream方法时,为什么要实现多态行为呢?

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

假设您正在编写一些通用的lib/framework,那么您只需要使用
Animal
class,它是所有其他子类(如
Dog)的基础,Cat
等,那么您不能像
Dog myDog或Cat myCat
那样声明您的成员,它应该在那里
Animal myAnimal
,以便它可以获取所有动物子类

Thast's why
animalArrayList
应该始终采用Animal及其变体,不会出现编译错误


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

欢迎使用。您的问题是什么?相关:您认为编译时错误会出现在哪里?请阅读Java教程。搜索和研究“Java多态性”和“Java方法重写”。