【发布时间】:2017-04-22 09:18:35
【问题描述】:
我一直在拼命想了解 Java 中 Object 类型转换的真正用途以及它为何存在。请参见下面的示例。
我的问题是下面cmets的形式。
请不要建议我去某个地方。我已经这样做了。知道的请直接回复我。谢谢。
检查此代码并覆盖方法 'scream' 我没有收到编译时错误。也看cmets
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?
【问题讨论】:
-
欢迎来到 SO。你有什么问题?
-
您预计会在哪里出现编译时错误?
-
阅读 Java 教程。搜索和研究“Java 多态”和“Java 方法覆盖”。
标签: java object-oriented-analysis typecasting-operator