What is the real significance(use) of polymorphism

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

    I guess sometimes objects are dynamically called. You are not sure whether the object would be a triangle, square etc in a classic shape poly. example.

    So, to leave all such things behind, we just call the function of derived class and assume the one of the dynamic class will be called.

    You wouldn't care if its a sqaure, triangle or rectangle. You just care about the area. Hence the getArea method will be called depending upon the dynamic object passed.

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

    Advantage of polymorphism is client code doesn't need to care about the actual implementation of a method. Take look at the following example. Here CarBuilder doesn't know anything about ProduceCar().Once it is given a list of cars (CarsToProduceList) it will produce all the necessary cars accordingly.

    class CarBase
    {
        public virtual void ProduceCar()
        {
            Console.WriteLine("don't know how to produce");
        }
    }
    
    class CarToyota : CarBase
    {
        public override void ProduceCar()
        {
            Console.WriteLine("Producing Toyota Car ");
        }
    }
    
    class CarBmw : CarBase
    {
        public override void ProduceCar()
        {
            Console.WriteLine("Producing Bmw Car");
        }
    }
    
    class CarUnknown : CarBase { }
    
    class CarBuilder
    {
        public List<CarBase> CarsToProduceList { get; set; }
    
        public void ProduceCars()
        {
            if (null != CarsToProduceList)
            {
                foreach (CarBase car in CarsToProduceList)
                {
                    car.ProduceCar();// doesn't know how to produce
                }
            }
    
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            CarBuilder carbuilder = new CarBuilder();
            carbuilder.CarsToProduceList = new List<CarBase>() { new CarBmw(), new CarToyota(), new CarUnknown() };            
            carbuilder.ProduceCars();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 02:08

    Classic answer: Imagine a base class Shape. It exposes a GetArea method. Imagine a Square class and a Rectangle class, and a Circle class. Instead of creating separate GetSquareArea, GetRectangleArea and GetCircleArea methods, you get to implement just one method in each of the derived classes. You don't have to know which exact subclass of Shape you use, you just call GetArea and you get your result, independent of which concrete type is it.

    Have a look at this code:

    #include <iostream>
    using namespace std;
    
    class Shape
    {
    public:
      virtual float GetArea() = 0;
    };
    
    class Rectangle : public Shape
    {
    public:
      Rectangle(float a) { this->a = a; }
      float GetArea() { return a * a; }
    private:
      float a;
    };
    
    class Circle : public Shape
    {
    public:
      Circle(float r) { this->r = r; }
      float GetArea() { return 3.14f * r * r; }
    private:
      float r;
    };
    
    int main()
    {
      Shape *a = new Circle(1.0f);
      Shape *b = new Rectangle(1.0f);
    
      cout << a->GetArea() << endl;
      cout << b->GetArea() << endl;
    }
    

    An important thing to notice here is - you don't have to know the exact type of the class you're using, just the base type, and you will get the right result. This is very useful in more complex systems as well.

    Have fun learning!

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

    Tabbed Applications

    A good application to me is generic buttons (for all tabs) within a tabbed-application - even the browser we are using it is implementing Polymorphism as it doesn't know the tab we are using at the compile-time (within the code in other words). Its always determined at the Run-time (right now! when we are using the browser.)

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

    One of the most significant benefit that you get from polymorphic operations is ability to expand. You can use same operations and not changing existing interfaces and implementations only because you faced necessity for some new stuff.

    All that we want from polymorphism - is simplify our design decision and make our design more extensible and elegant. You should also draw attention to Open-Closed Principle (http://en.wikipedia.org/wiki/Open/closed_principle) and for SOLID (http://en.wikipedia.org/wiki/Solid_%28Object_Oriented_Design%29) that can help you to understand key OO principles.

    P.S. I think you are talking about "Dynamic polymorphism" (http://en.wikipedia.org/wiki/Dynamic_polymorphism), because there are such thing like "Static polymorphism" (http://en.wikipedia.org/wiki/Template_metaprogramming#Static_polymorphism).

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

    Polymorphism allows you to write code that uses objects. You can then later create new classes that your existing code can use with no modification.

    For example, suppose you have a function Lib2Groc(vehicle) that directs a vehicle from the library to the grocery store. It needs to tell vehicles to turn left, so it can call TurnLeft() on the vehicle object among other things. Then if someone later invents a new vehicle, like a hovercraft, it can be used by Lib2Groc with no modification.

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