多态——对象和类型 [英] Polymorphism - object and type

查看:64
本文介绍了多态——对象和类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对多态中的子类引用为超类"的概念有些困惑.(参考此处:https://stackify.com/oop-concept-polymorphism/)

I'm a bit confused on the concept of 'Subclass referenced as Superclass' within polymorphism. (referencing here: https://stackify.com/oop-concept-polymorphism/)

假设我们有超类动物和子类狗,其中狗扩展了动物.以下工作:

Lets say we have the superclass animal and the subclass dog, where dog extends animal. The following work:

  1. animal testSuper = new Animal();
  2. dog testDog = new dog();
  3. animal testSuperDog = new dog();

谁能进一步解释一下#3 的幕后情况?当我们执行 'new dog()' 时,我们是否创建了 dog 类的对象,但是当我们执行 'animal testSuperDog' 时,我们将其转换为超类动物?或者是相反的 - 'animal testSuperDog' 创建了一个动物对象,但是当我们执行 'new dog()' 时,我们将其转换为子类 dog?

Could anyone explain a bit further on whats happening behind the scenes for #3? When we do 'new dog()', are we creating an object of the dog class but when we do 'animal testSuperDog' we cast it to the superclass animal? Or is it the other way around - 'animal testSuperDog' creates an animal object but we're casting it down to the subclass dog when we do 'new dog()'?

我尝试了第四个排列来探索,但我收到一个类型不匹配错误,说它无法从动物转换为狗.所以这就是为什么我假设正在进行一些转换.4. dog testSubdog = new Animal();

I've tried the 4th permutation to explore and I get a type mismatch error saying that it can't convert from animal to dog. So that's why I'm assuming there's some conversion going on. 4. dog testSubdog = new animal();

如果我们可以深入挖掘一下,既然我们知道 #3 有效,那么这样做的好处/用例是什么?

If we can dig a bit deeper, since we know #3 works, whats the benefit / use case of this?

  1. testDog.noise();
  2. testSuperDog.noise();

这两种方法都将使用子类 dog 的 'noise' 方法.

Both these would use the 'noise' method from the subclass dog.

推荐答案

如果我们可以深入挖掘一下,既然我们知道 #3 有效,那么这样做的好处/用例是什么?

If we can dig a bit deeper, since we know #3 works, whats the benefit / use case of this?

假设您有一个 Person 类:

public class Person {
    String name;
    Animal pet;

    public Person(String name, Animal pet) {
        this.name = name;
        this.pet = pet;
    }
}

宠物可以是狗、猫或其他

Pet can be dog, cat or other

Animal dog = new Dog();
Animal cat = new Cat();
Persion john = new Persion("john", dog);
Persion lia = new Persion("lia", cat);

Cat 和 Dog 类必须扩展为 Animal

Class Cat and Dog must be extend Animal

如果您想要一个动物列表并将其设置在循环中?

Animal dog = new Dog();
Animal cat = new Cat();
List<Animal> list = new ArrayList<>();
list.add(cat);
list.add(dog);

for(Animal animal : list)
    animal.noise();

还有很多其他的情况.您可以研究:

And there are many other cases. You can reseach for:

  1. 坚实的设计原则
  2. Spring 框架的依赖注入

这篇关于多态——对象和类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆