What is polymorphism, what is it for, and how is it used?

I was watching a Google Tech Talks video, and they frequently referred to polymorphism.

What is polymorphism, what is it for, and how is it used?


If you think about the Greek roots of the term, it should become obvious.

  • Poly = many: polygon = many-sided, polystyrene = many styrenes (a), polyglot = many languages, and so on.
  • Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any form.
  • So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).

    For example, in many languages, integers and floats are implicitly polymorphic since you can add, subtract, multiply and so on, irrespective of the fact that the types are different. They're rarely considered as objects in the usual term.

    But, in that same way, a class like BigDecimal or Rational or Imaginary can also provide those operations, even though they operate on different data types.

    The classic example is the Shape class and all the classes that can inherit from it (square, circle, dodecahedron, irregular polygon, splat and so on).

    With polymorphism, each of these classes will have different underlying data. A point shape needs only two co-ordinates (assuming it's in a two-dimensional space of course). A circle needs a center and radius. A square or rectangle needs two co-ordinates for the top left and bottom right corners and (possibly) a rotation. An irregular polygon needs a series of lines.

    By making the class responsible for its code as well as its data, you can achieve polymorphism. In this example, every class would have its own Draw() function and the client code could simply do:

    shape.Draw()
    

    to get the correct behavior for any shape.

    This is in contrast to the old way of doing things in which the code was separate from the data, and you would have had functions such as drawSquare() and drawCircle() .

    Object orientation, polymorphism and inheritance are all closely-related concepts and they're vital to know. There have been many "silver bullets" during my long career which basically just fizzled out but the OO paradigm has turned out to be a good one. Learn it, understand it, love it - you'll be glad you did :-)


    (a) I originally wrote that as a joke but it turned out to be correct and, therefore, not that funny. The momomer styrene happens to be made from carbon and hydrogen, C8H8 , and polystyrene is made from groups of that, (C8H8)n .

    Perhaps I should have stated that a polyp was many occurrences of the letter p although, now that I've had to explain the joke, even that doesn't seem funny either.

    Sometimes, you should just quit while you're behind :-)


    Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.

    Here is an example in C#. Create four classes within a console application:

    public abstract class Vehicle
    {
        public abstract int Wheels;
    }
    
    public class Bicycle : Vehicle
    {
        public override int Wheels()
        {
            return 2;
        }
    }
    
    public class Car : Vehicle
    {
        public override int Wheels()
        {
            return 4;
        }
    }
    
    public class Truck : Vehicle
    {
        public override int Wheels()
        {
            return 18;
        }
    }
    

    Now create the following in the Main() of the module for the console application:

    public void Main()
    {
        List<Vehicle> vehicles = new List<Vehicle>();
    
        vehicles.Add(new Bicycle());
        vehicles.Add(new Car());
        vehicles.Add(new Truck());
    
        foreach (Vehicle v in vehicles)
        {
            Console.WriteLine(
                string.Format("A {0} has {1} wheels.",
                    v.GetType().Name, v.Wheels));
        }
    }
    

    In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.

    We then add a Bicycle, Car and Truck to the list.

    Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.

    This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.

    I hope that this helps you.


    From Understanding and Applying Polymorphism in PHP, Thanks Steve Guidetti.

    Polymorphism is a long word for a very simple concept.

    Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.

    The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they're all used the same way. A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.

    In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.

    链接地址: http://www.djcxy.com/p/43082.html

    上一篇: 如何创建一个polyvariadic haskell函数?

    下一篇: 什么是多态,什么是它,以及它是如何使用的?