Polymorphism vs Inheritance

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

    If you are certain that it will always be a dog there is no reason for it. You might aswell use Dog d = new Dog(); as you described. But let's say you used a method instead of a constructor. The method returned an animal and you wouldn't know which implementation of animal you would get. You would still be able to use the same methods on the animal (even if it's a Dog, Elephant cat etc).

    For extensibility purposes inheritance simplifies things. When you want to create an elephant or cat which also share some animal methods, You can easily get those by having animal as super class.

提交回复
热议问题