【问题标题】:What is the point of Object Implicit type casting?对象隐式类型转换有什么意义?
【发布时间】: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


【解决方案1】:

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

认为您正在编写一些通用库/框架,那么您想要使用的只是 Animal 类,它是所有其他子类(如 Dog, Cat 等)的基础,那么您不能像 Dog myDog or Cat myCat 这样声明您的成员,它应该在那里是Animal myAnimal,这样它就可以接受所有的动物子类。

这就是为什么animalArrayList 应该始终采用 Animal 及其变体,不会出现编译错误。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-24
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2011-07-26
    • 1970-01-01
    • 2011-01-07
    相关资源
    最近更新 更多