Polymorphism vs Inheritance

后端 未结 6 1570
青春惊慌失措
青春惊慌失措 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 21:07

    You can have other implementations of the Animal class, such as Cat. Then you can say

    Animal a = new Dog();
    Animal b = new Cat();
    

    You can call methods of the Animal class without caring which implementation it really is, and polymorphism will call the correct method. E.g.

    a.speak();  // "Woof"
    
    b.speak();  // "Meow"
    

    Really, it's not "Polymorphism vs Inheritance" but "Polymorphism using Inheritance".

提交回复
热议问题