What is the real significance(use) of polymorphism

前端 未结 10 2300
别跟我提以往
别跟我提以往 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<T>. Big pain in the butt, right?

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

    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.

    0 讨论(0)
  • 2020-12-01 02:21

    Polymorphism is the foundation of Object Oriented Programming. It means that one object can be have as another project. So how does on object can become other, its possible through following

    1. Inheritance
    2. Overriding/Implementing parent Class behavior
    3. Runtime Object binding

    One of the main advantage of it is switch implementations. Lets say you are coding an application which needs to talk to a database. And you happen to define a class which does this database operation for you and its expected to do certain operations such as Add, Delete, Modify. You know that database can be implemented in many ways, it could be talking to file system or a RDBM server such as MySQL etc. So you as programmer, would define an interface that you could use, such as...

    public interface DBOperation {
        public void addEmployee(Employee newEmployee);
        public void modifyEmployee(int id, Employee newInfo);
        public void deleteEmployee(int id);
    }
    

    Now you may have multiple implementations, lets say we have one for RDBMS and other for direct file-system

    public class DBOperation_RDBMS implements DBOperation
        // implements DBOperation above stating that you intend to implement all
        // methods in DBOperation
        public void addEmployee(Employee newEmployee) {
              // here I would get JDBC (Java's Interface to RDBMS) handle
              // add an entry into database table.
        }
        public void modifyEmployee(int id, Employee newInfo) {
              // here I use JDBC handle to modify employee, and id to index to employee
        }
        public void deleteEmployee(int id) {
              // here I would use JDBC handle to delete an entry
        }
    }
    

    Lets have File System database implementation

    public class DBOperation_FileSystem implements DBOperation
        public void addEmployee(Employee newEmployee) {
              // here I would Create a file and add a Employee record in to it
        }
        public void modifyEmployee(int id, Employee newInfo) {
              // here I would open file, search for record and change values
        }
        public void deleteEmployee(int id) {
              // here I search entry by id, and delete the record
        }
    }
    

    Lets see how main can switch between the two

    public class Main {
        public static void main(String[] args) throws Exception {
              Employee emp = new Employee();
              ... set employee information
    
              DBOperation dboper = null;
              // declare your db operation object, not there is no instance
              // associated with it
    
              if(args[0].equals("use_rdbms")) {
                   dboper = new DBOperation_RDBMS();
                   // here conditionally, i.e when first argument to program is
                   // use_rdbms, we instantiate RDBM implementation and associate
                   // with variable dboper, which delcared as DBOperation.
                   // this is where runtime binding of polymorphism kicks in
                   // JVM is allowing this assignment because DBOperation_RDBMS
                   // has a "is a" relationship with DBOperation.
              } else if(args[0].equals("use_fs")) {
                   dboper = new DBOperation_FileSystem(); 
                   // similarly here conditionally we assign a different instance.
              } else {
                   throw new RuntimeException("Dont know which implemnation to use");
              }
    
              dboper.addEmployee(emp);
              // now dboper is refering to one of the implementation 
              // based on the if conditions above
              // by this point JVM knows dboper variable is associated with 
              // 'a' implemenation, and it will call appropriate method              
        }
    }
    

    You can use polymorphism concept in many places, one praticle example would be: lets you are writing image decorer, and you need to support the whole bunch of images such as jpg, tif, png etc. So your application will define an interface and work on it directly. And you would have some runtime binding of various implementations for each of jpg, tif, pgn etc.

    One other important use is, if you are using java, most of the time you would work on List interface, so that you can use ArrayList today or some other interface as your application grows or its needs change.

    0 讨论(0)
  • 2020-12-01 02:22

    Have you ever added two integers with +, and then later added an integer to a floating-point number with +?

    Have you ever logged x.toString() to help you debug something?

    I think you probably already appreciate polymorphism, just without knowing the name.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题