Can someone explain the benefits of polymorphism?

前端 未结 10 469
难免孤独
难免孤独 2021-02-01 10:41

So I understand pretty much how it works, but I just can\'t grasp what makes it useful. You still have to define all the separate functions, you still have to create an instanc

10条回答
  •  天涯浪人
    2021-02-01 11:39

    Let's say that my School class has a educate() method. This method accepts only people who can learn. They have different styles of learning. Someone grasps, someone just mugs it up, etc.

    Now lets say I have boys, girls, dogs, and cats around the School class. If School wants to educate them, I would have to write different methods for the different objects, under School.

    Instead, the different people Objects (boys,girls , cats..) implement the Ilearnable interface. Then, the School class does not have to worry about what it has to educate.

    School will just have to write a

    public void Educate (ILearnable  anyone)
    

    method.

    I have written cats and dogs because they might want to visit different type of school. As long as it is certain type of school (PetSchool : School) and they can Learn, they can be educated.

    1. So it saves multiple methods that have the same implementation but different input types
    2. The implementation matches the real life scenes and so it's easy for design purposes
    3. We can concentrate on part of the class and ignore everything else.
    4. Extension of the class (e.g. After years of education you come to know, hey, all those people around the School must go through GoGreen program where everyone must plant a tree in the same way. Here if you had a base class of all those people as abstract LivingBeings, we can add a method to call PlantTree and write code in PlantTree. Nobody needs to write code in their Class body as they inherit from the LivingBeings class, and just typecasting them to PlantTree will make sure they can plant trees).

提交回复
热议问题