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

前端 未结 28 2762
南笙
南笙 2020-11-21 07:08

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

相关标签:
28条回答
  • 2020-11-21 07:37

    Polymorphism is the ability to treat a class of object as if it is the parent class.

    For instance, suppose there is a class called Animal, and a class called Dog that inherits from Animal. Polymorphism is the ability to treat any Dog object as an Animal object like so:

    Dog* dog = new Dog;
    Animal* animal = dog;
    
    0 讨论(0)
  • 2020-11-21 07:38

    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.

    0 讨论(0)
  • 2020-11-21 07:38

    Polymorphism:

    Different execution according to the instance of the class, not the type of reference variable.

    An interface type reference variable can refer to any of the class instances that implement that interface.

    0 讨论(0)
  • 2020-11-21 07:39

    Generally speaking, it's the ability to interface a number of different types of object using the same or a superficially similar API. There are various forms:

    • Function overloading: defining multiple functions with the same name and different parameter types, such as sqrt(float), sqrt(double) and sqrt(complex). In most languages that allow this, the compiler will automatically select the correct one for the type of argument being passed into it, thus this is compile-time polymorphism.

    • Virtual methods in OOP: a method of a class can have various implementations tailored to the specifics of its subclasses; each of these is said to override the implementation given in the base class. Given an object that may be of the base class or any of its subclasses, the correct implementation is selected on the fly, thus this is run-time polymorphism.

    • Templates: a feature of some OO languages whereby a function, class, etc. can be parameterised by a type. For example, you can define a generic "list" template class, and then instantiate it as "list of integers", "list of strings", maybe even "list of lists of strings" or the like. Generally, you write the code once for a data structure of arbitrary element type, and the compiler generates versions of it for the various element types.

    0 讨论(0)
  • 2020-11-21 07:39

    Polymorphism is the ability of the programmer to write methods of the same name that do different things for different types of objects, depending on the needs of those objects. For example, if you were developing a class called Fraction and a class called ComplexNumber, both of these might include a method called display(), but each of them would implement that method differently. In PHP, for example, you might implement it like this:

    //  Class definitions
    
    class Fraction
    {
        public $numerator;
        public $denominator;
    
        public function __construct($n, $d)
        {
            //  In real life, you'd do some type checking, making sure $d != 0, etc.
            $this->numerator = $n;
            $this->denominator = $d;
        }
    
        public function display()
        {
            echo $this->numerator . '/' . $this->denominator;
        }
    }
    
    class ComplexNumber
    {
        public $real;
        public $imaginary;
    
        public function __construct($a, $b)
        {
            $this->real = $a;
            $this->imaginary = $b;
        }
    
        public function display()
        {
            echo $this->real . '+' . $this->imaginary . 'i';
        }
    }
    
    
    //  Main program
    
    $fraction = new Fraction(1, 2);
    $complex = new ComplexNumber(1, 2);
    
    echo 'This is a fraction: '
    $fraction->display();
    echo "\n";
    
    echo 'This is a complex number: '
    $complex->display();
    echo "\n";
    

    Outputs:

    This is a fraction: 1/2
    This is a complex number: 1 + 2i
    

    Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe Fraction and ComplexNumber both implement an abstract class called Number that has a method display(), which Fraction and ComplexNumber are then both obligated to implement. But you don't need inheritance to take advantage of polymorphism.

    At least in dynamically-typed languages like PHP (I don't know about C++ or Java), polymorphism allows the developer to call a method without necessarily knowing the type of object ahead of time, and trusting that the correct implementation of the method will be called. For example, say the user chooses the type of Number created:

    $userNumberChoice = $_GET['userNumberChoice'];
    
    switch ($userNumberChoice) {
        case 'fraction':
            $userNumber = new Fraction(1, 2);
            break;
        case 'complex':
            $userNumber = new ComplexNumber(1, 2);
            break;
    }
    
    echo "The user's number is: ";
    $userNumber->display();
    echo "\n";
    

    In this case, the appropriate display() method will be called, even though the developer can't know ahead of time whether the user will choose a fraction or a complex number.

    0 讨论(0)
  • 2020-11-21 07:40

    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.

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