What is the real significance(use) of polymorphism

前端 未结 10 2336
别跟我提以往
别跟我提以往 2020-12-01 01:44

I am new to OOP. Though I understand what polymorphism is, but I can\'t get the real use of it. I can have functions with different name. Why should I try to implement polym

10条回答
  •  天命终不由人
    2020-12-01 02:17

    You don't need polymorphism.

    Until you do.

    Then its friggen awesome.

    Simple answer that you'll deal with lots of times:

    Somebody needs to go through a collection of stuff. Let's say they ask for a collection of type MySpecializedCollectionOfAwesome. But you've been dealing with your instances of Awesome as List. So, now, you're going to have to create an instance of MSCOA and fill it with every instance of Awesome you have in your List. Big pain in the butt, right?

    Well, if they asked for an IEnumerable, you could hand them one of MANY collections of Awesome. You could hand them an array (Awesome[]) or a List (List) or an observable collection of Awesome or ANYTHING ELSE you keep your Awesome in that implements IEnumerable.

    The power of polymorphism lets you be type safe, yet be flexible enough that you can use an instance many many different ways without creating tons of code that specifically handles this type or that type.

提交回复
热议问题