Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C# Polymorphism

C# Polymorphism

Polymorphism is the ability of the same behavior to have multiple different forms or manifestations.

Polymorphismmeans having multiple forms. In the object-oriented programming paradigm, polymorphism often manifests as "one interface, multiple functions".

Polymorphism can be static or dynamic. Instatic polymorphism, the response of a function occurs at compile time. Indynamic polymorphism, the response of a function occurs at runtime.

In C#, every type is polymorphic because all types, including user-defined ones, inherit from Object.

Polymorphism means using the same interface with different instances to perform different operations, as shown in the figure:

In reality, for example, the action of pressing the F1 key:

  • If you are currently in the Flash interface, the AS 3 help document pops up;
  • If you are currently in Word, the Word help pops up;
  • In Windows, the Windows Help and Support pops up.
  • The same event occurring on different objects produces different results.

    static polymorphism

    At compile time, the mechanism of connecting a function and an object is called early binding, also known as static binding. C# provides two techniques to achieve static polymorphism, namely:

    Operator overloading will be discussed in the next chapter; next we will discuss function overloading.


    function overloading

    You can have multiple definitions for the same function name within the same scope. The definitions must differ from one another, either in the parameter types in the parameter list or in the number of parameters. Function declarations that differ only in return type do not count as different overloads.

    The following example demonstrates several functions with the same name Add(), used to add different numbers of parameters:

    Example

    using

    System

    ;

    namespace

    PolymorphismApplication

    {

       

    public

    class

    TestData  

       

    {

     

           

    public

    int

    Add

    (

    int

    a,

    int

    b,

    int

    c

    )

     

           

    {

     

               

    return

    a

    b

    c

    ;

     

           

    }

     

           

    public

    int

    Add

    (

    int

    a,

    int

    b

    )

     

           

    {

     

               

    return

    a

    b

    ;

     

           

    }

     

       

    }

     

       

    class

    Program  

       

    {

     

           

    static

    void

    Main

    (

    string

    [

    ]

    args

    )

     

           

    {

     

                TestData dataClass

    =

    new

    TestData

    (

    )

    ;

               

    int

    add1

    =

    dataClass

    .

    Add

    (

    1

    ,

    2

    )

    ;

     

               

    int

    add2

    =

    dataClass

    .

    Add

    (

    1

    ,

    2

    ,

    3

    )

    ;

                Console

    .

    WriteLine

    (

    "add1 :"

    add1

    )

    ;

                Console

    .

    WriteLine

    (

    "add2 :"

    add2

    )

    ;

     

           

    }

     

       

    }

     

    }

    The following example demonstrates several functions with the same name print(), used to print different data types:

    Example

    using

    System

    ;

    namespace

    PolymorphismApplication

    {

       

    class

    Printdata

       

    {

         

    void

    print

    (

    int

    i

    )

         

    {

             Console

    .

    WriteLine

    (

    "Output integer: {0}"

    , i

    )

    ;

         

    }

         

    void

    print

    (

    double

    f

    )

         

    {

             Console

    .

    WriteLine

    (

    "Output floating-point: {0}"

    , f

    )

    ;

         

    }

         

    void

    print

    (

    string

    s

    )

         

    {

             Console

    .

    WriteLine

    (

    "Output string: {0}"

    , s

    )

    ;

         

    }

         

    static

    void

    Main

    (

    string

    [

    ]

    args

    )

         

    {

             Printdata p

    =

    new

    Printdata

    (

    )

    ;

             

    // Call print to output an integer

             p

    .

    print

    (

    1

    )

    ;

             

    // Call print to output a floating-point number

             p

    .

    print

    (

    1.23

    )

    ;

             

    // Call print to output a string

             p

    .

    print

    (

    "Hello Runoob"

    )

    ;

             Console

    .

    ReadKey

    (

    )

    ;

         

    }

       

    }

    }

    When the code above is compiled and executed, it produces the following result:

    
    
    输出整型: 1
    
    输出浮点型: 1.23
    
    输出字符串: Hello Runoob
    
    

    dynamic polymorphism

    C# allows you to use the keyword abstract to create an abstract class, which provides a partial implementation of an interface. When a derived class inherits from the abstract class, the implementation is completed.abstract classesAn abstract class can contain abstract methods, which can be implemented by derived classes. Derived classes have more specialized functionality.

    Note the following rules about abstract classes:

    The following program demonstrates an abstract class:

    Example

    using

    System

    ;

    namespace

    PolymorphismApplication

    {

       

    abstract

    class

    Shape

       

    {

           

    abstract

    public

    int

    area

    (

    )

    ;

       

    }

       

    class

    Rectangle

    :

     Shape

       

    {

         

    private

    int

    length

    ;

         

    private

    int

    width

    ;

         

    public

    Rectangle

    (

    int

    a

    =

    0

    ,

    int

    b

    =

    0

    )

         

    {

             length

    =

    a

    ;

             width

    =

    b

    ;

         

    }

         

    public

    override

    int

    area

    (

    )

         

    {

             Console

    .

    WriteLine

    (

    "Area of the Rectangle class:"

    )

    ;

             

    return

    (

    width

    length

    )

    ;

         

    }

       

    }

       

    class

    RectangleTester

       

    {

         

    static

    void

    Main

    (

    string

    [

    ]

    args

    )

         

    {

             Rectangle r

    =

    new

    Rectangle

    (

    10

    ,

    7

    )

    ;

             

    double

    a

    =

    r

    .

    area

    (

    )

    ;

             Console

    .

    WriteLine

    (

    "Area: {0}"

    ,a

    )

    ;

             Console

    .

    ReadKey

    (

    )

    ;

         

    }

       

    }

    }

    When the code above is compiled and executed, it produces the following result:

    
    
    Area of the Rectangle class:
    
    面积: 70
    
    

    When a function defined in a class needs to be implemented in an inheriting class, you can use avirtual method。

    A virtual method is declared with the keyword virtual virtual.

    A virtual method can have different implementations in different inherited classes.

    Calls to a virtual method occur at runtime.

    Dynamic polymorphism is achieved through abstract classes and virtual method implementation.

    The following example creates a base class Shape and derived classes Circle, Rectangle, and Triangle. The Shape class provides a virtual method named Draw, which is overridden in each derived class to draw the specific shape of that class.

    Example

    using

    System

    ;

    using

    System.Collections.Generic

    ;

    public

    class

    Shape

    {

       

    public

    int

    X

    {

    get

    ;

    private

    set

    ;

    }

       

    public

    int

    Y

    {

    get

    ;

    private

    set

    ;

    }

       

    public

    int

    Height

    {

    get

    ;

    set

    ;

    }

       

    public

    int

    Width

    {

    get

    ;

    set

    ;

    }

       

       

    // Virtual method

       

    public

    virtual

    void

    Draw

    (

    )

       

    {

            Console

    .

    WriteLine

    (

    "Performing the base class drawing task"

    )

    ;

       

    }

    }

    class

    Circle

    :

    Shape

    {

       

    public

    override

    void

    Draw

    (

    )

       

    {

            Console

    .

    WriteLine

    (

    "Drawing a circle"

    )

    ;

           

    base

    .

    Draw

    (

    )

    ;

       

    }

    }

    class

    Rectangle

    :

    Shape

    {

       

    public

    override

    void

    Draw

    (

    )

       

    {

            Console

    .

    WriteLine

    (

    "Drawing a rectangle"

    )

    ;

           

    base

    .

    Draw

    (

    )

    ;

       

    }

    }

    class

    Triangle

    :

    Shape

    {

       

    public

    override

    void

    Draw

    (

    )

       

    {

            Console

    .

    WriteLine

    (

    "Drawing a triangle"

    )

    ;

           

    base

    .

    Draw

    (

    )

    ;

       

    }

    }

    class

    Program

    {

       

    static

    void

    Main

    (

    string

    [

    ]

    args

    )

       

    {

           

    // Create a List object, and add Circle, Triangle, and Rectangle to it

           

    var

    shapes

    =

    new

    List

    <
    
    Shape
    
    {
    
    new
    
    Rectangle
    
    (
    
    )
    
    ,
    
    new
    
    Triangle
    
    (
    
    )
    
    ,
    
    new
    
    Circle
    
    (
    
    )
    
    }

    ;

           

    // Use a foreach loop to iterate over the derived classes in the list and call the Draw method on each Shape object

           

    foreach

    (

    var

    shape

    in

    shapes

    )

           

    {

                shape

    .

    Draw

    (

    )

    ;

           

    }

            Console

    .

    WriteLine

    (

    "Press any key to exit."

    )

    ;

            Console

    .

    ReadKey

    (

    )

    ;

       

    }

    }

    When the code above is compiled and executed, it produces the following result:

    
    
    画一个长方形
    
    执行基类的画图任务
    
    画一个三角形
    
    执行基类的画图任务
    
    画一个圆形
    
    执行基类的画图任务
    
    按下任意键退出。
    
    

    The following program demonstrates calculating the area of different shapes through the virtual method area():

    Example

    using

    System

    ;

    namespace

    PolymorphismApplication

    {

       

    class

    Shape

       

    {

         

    protected

    int

    width, height

    ;

         

    public

    Shape

    (

    int

    a

    =

    0

    ,

    int

    b

    =

    0

    )

         

    {

             width

    =

    a

    ;

             height

    =

    b

    ;

         

    }

         

    public

    virtual

    int

    area

    (

    )

         

    {

             Console

    .

    WriteLine

    (

    "Area of the parent class:"

    )

    ;

             

    return

    0

    ;

         

    }

       

    }

       

    class

    Rectangle

    :

    Shape

       

    {

         

    public

    Rectangle

    (

    int

    a

    =

    0

    ,

    int

    b

    =

    0

    )

    :

    base

    (

    a, b

    )

         

    {

         

    }

         

    public

    override

    int

    area

    (

    )

         

    {

             Console

    .

    WriteLine

    (

    "Area of the Rectangle class:"

    )

    ;

             

    return

    (

    width

    height

    )

    ;

         

    }

       

    }

       

    class

    Triangle

    :

    Shape

       

    {

         

    public

    Triangle

    (

    int

    a

    =

    0

    ,

    int

    b

    =

    0

    )

    :

    base

    (

    a, b

    )

         

    {

         

         

    }

         

    public

    override

    int

    area

    (

    )

         

    {

             Console

    .

    WriteLine

    (

    "Area of the Triangle class:"

    )

    ;

             

    return

    (

    width

    height

    /

    2

    )

    ;

         

    }

       

    }

       

    class

    Caller

       

    {

         

    public

    void

    CallArea

    (

    Shape sh

    )

         

    {

             

    int

    a

    ;

             a

    =

    sh

    .

    area

    (

    )

    ;

             Console

    .

    WriteLine

    (

    "Area: {0}"

    , a

    )

    ;

         

    }

       

    }

     

       

    class

    Tester

       

    {

         

         

    static

    void

    Main

    (

    string

    [

    ]

    args

    )

         

    {

             Caller c

    =

    new

    Caller

    (

    )

    ;

             Rectangle r

    =

    new

    Rectangle

    (

    10

    ,

    7

    )

    ;

             Triangle t

    =

    new

    Triangle

    (

    10

    ,

    5

    )

    ;

             c

    .

    CallArea

    (

    r

    )

    ;

             c

    .

    CallArea

    (

    t

    )

    ;

             Console

    .

    ReadKey

    (

    )

    ;

         

    }

       

    }

    }

    When the code above is compiled and executed, it produces the following result:

    
    
    Area of the Rectangle class:
    
    面积:70
    
    Area of the Triangle class:
    
    面积:25