What is the real significance(use) of polymorphism

前端 未结 10 2357
别跟我提以往
别跟我提以往 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:26

    In a strictly typed language, polymorphism is important in order to have a list/collection/array of objects of different types. This is because lists/arrays are themselves typed to contain only objects of the correct type.

    Imagine for example we have the following:

    // the following is pseudocode M'kay:
    class apple;
    class banana;
    class kitchenKnife;
    
    apple foo;
    banana bar;
    kitchenKnife bat;
    
    apple *shoppingList = [foo, bar, bat]; // this is illegal because bar and bat is
                                           // not of type apple.
    

    To solve this:

    class groceries;
    class apple inherits groceries;
    class banana inherits groceries;
    class kitchenKnife inherits groceries;
    
    apple foo;
    banana bar;
    kitchenKnife bat;
    
    groceries *shoppingList = [foo, bar, bat]; // this is OK
    

    Also it makes processing the list of items more straightforward. Say for example all groceries implements the method price(), processing this is easy:

    int total = 0;
    foreach (item in shoppingList) {
        total += item.price();
    }
    

    These two features are the core of what polymorphism does.

提交回复
热议问题