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

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

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

28条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 07:56

    What is polymorphism?

    Polymorphism is the ability to:

    • Invoke an operation on an instance of a specialized type by only knowing its generalized type while calling the method of the specialized type and not that of the generalized type: it is dynamic polymorphism.

    • Define several methods having the save name but having differents parameters: it is static polymorphism.

    The first if the historical definition and the most important.

    What is polymorphism used for?

    It allows to create strongly-typed consistency of the class hierarchy and to do some magical things like managing lists of objects of differents types without knowing their types but only one of their parent type, as well as data bindings.

    Strong and weak typing

    Sample

    Here are some Shapes like Point, Line, Rectangle and Circle having the operation Draw() taking either nothing or either a parameter to set a timeout to erase it.

    public class Shape
    {
     public virtual void Draw()
     {
       DoNothing();
     }
     public virtual void Draw(int timeout)
     {
       DoNothing();
     }
    }
    
    public class Point : Shape
    {
     int X, Y;
     public override void Draw()
     {
       DrawThePoint();
     }
    }
    
    public class Line : Point
    {
     int Xend, Yend;
     public override Draw()
     {
       DrawTheLine();
     }
    }
    
    public class Rectangle : Line
    {
     public override Draw()
     {
       DrawTheRectangle();
     }
    }
    
    var shapes = new List { new Point(0,0), new Line(0,0,10,10), new rectangle(50,50,100,100) };
    
    foreach ( var shape in shapes )
      shape.Draw();
    

    Here the Shape class and the Shape.Draw() methods should be marked as abstract.

    They are not for to make understand.

    Explaination

    Without polymorphism, using abstract-virtual-override, while parsing the shapes, it is only the Spahe.Draw() method that is called as the CLR don't know what method to call. So it call the method of the type we act on, and here the type is Shape because of the list declaration. So the code do nothing at all.

    With polymorphism, the CLR is able to infer the real type of the object we act on using what is called a virtual table. So it call the good method, and here calling Shape.Draw() if Shape is Point calls the Point.Draw(). So the code draws the shapes.

    More readings

    C# - Polymorphism (Level 1)

    Polymorphism in Java (Level 2)

    Polymorphism (C# Programming Guide)

    Virtual method table

提交回复
热议问题