繁体   English   中英

多态性 - object 和类型

[英]Polymorphism - object and type

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

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

  1. 动物测试超级=新动物();
  2. 狗 testDog = 新狗();
  3. 动物 testSuperDog = new dog();

任何人都可以进一步解释#3幕后发生的事情吗? 当我们执行“new dog()”时,我们是否创建了狗 class 的 object,但是当我们执行“animal testSuperDog”时,我们将其转换为超类动物? 或者是相反的方式 - 'animal testSuperDog' 创建了一个动物 object 但我们在执行 'new dog()' 时将其转换为子类 dog?

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

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

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

这两个都将使用子类 dog 的 'noise' 方法。

多态性,一个 object 的属性,具有许多不同的 forms。 To put this more precisely, a Java object may be accessed using a reference with the same type as the object, a reference that is a superclass of the object, or a reference that defines an interface the object implements, either directly or through a superclass .

所以对于你的第一个问题animal testSuperDog = new dog(); java 创建了一个狗 object 并且引用是一个动物你只能使用动物 object 中的方法。

旁注: class 名称应以大写字母开头

对于第二个问题,您创建了一条狗 object 并且必须表现得像一条狗,因此它使用被覆盖的方法,而不能在超类中使用方法

一个理解多态性的例子:

public class Reptile {
  public String getName() {
     return "Reptile";
  }
}
public class Alligator extends Reptile {
  public String getName() {
    return "Alligator";
  }
}
public class Crocodile extends Reptile {
  public String getName() {
    return "Crocodile";
  }
}
public class ZooWorker {
  public static void feed(Reptile reptile) {
    System.out.println("Feeding reptile "+reptile.getName());
  }

  public static void main(String[] args) {
    feed(new Alligator());
    feed(new Crocodile());
    feed(new Reptile());
  }
}

此代码编译和执行没有问题,产生以下 output:

Feeding: Alligator
Feeding: Crocodile
Feeding: Reptile

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

假设您有一个人 class:

public class Person {
    String name;
    Animal pet;

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

宠物可以是狗、猫或其他

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

Class 猫和狗必须是扩展动物

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

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();

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM