Polymorphism vs Inheritance

后端 未结 6 1426
青春惊慌失措
青春惊慌失措 2021-02-01 20:23

Suppose I have two classes: Animal and Dog. Dog is a subclass of Animal. I do the following code:

Animal a = new Dog();

Now I can call methods

6条回答
  •  离开以前
    2021-02-01 20:51

    Normally the question you've asked is more similar to Inheritance vs Composition :) More "real life" example of why it's good to use polymorphism is for example usage of strategy design pattern. You can have many TaxPolicy implementation: UsaTaxPolicy, CanadaTaxPolicy, EuTaxPolicy, etc. If you have method calculateFinalPrice, which have to also calculate tax, then you inject the proper implementation and good calculation is executed, no matter you've passed Usa, Canada or Eu implementation.

提交回复
热议问题