Understanding polymorphism parameter

Hi all,

It has been said that polymorphism is oftenly use for polymorhphic parameter.

example

Code:


void MyMethode(BaseClass a){...}

....

DerivedFromBaseClass d = new DerivedFromBaseClass();

MyMethode(d);


Why do we do this Why not have a method that take directly the DerivedFromBaseClass directly

I imagine is that while developping, sometime you just don't know the exact type that the method will take. So you pass take a BaseClass as parameter.


Answer this question

Understanding polymorphism parameter

  • EdenR

    Hi GoDaddy,

    What you are explaining is not really polymorphism, I think. It's just simple inheritance. By accepting a parameter of type BaseClass in your method you factor in some extensibility. Someone who uses your library can inherit from baseclass and pass along their class to MyMethod without the need to change your library.

    Polymorphism is where BaseClass has a method A() that exposes a certain behavior. Let's say you want to let classes that inherit from BaseClass change the behavior of A() without changing the base class. In C# you would define A() either as virtual or abstract on the BaseClass, and as override on the inherited classes.

    see http://msdn2.microsoft.com/en-us/ms173152.aspx for more info.

    A common example is where you have a class Dog that has a virtual method Bark(). It's easy to create a subclass Poodle : Dog that overrides Bark() with a high-pitched voice, and another subclass GreatDane : Dog that overrides the same method with a low-pitched voice.

    cheers,

    Stephane



  • Clemenza

    How about something like this:

    abstract class DrawItem
    {
    public abstract void Draw(Graphics g) { ... }
    }

    class Circle : DrawItem ...

    class Rectangle : DrawItem ...

    class Line : DrawItem ...

    Now you got a class that is your drawing pane and you want to draw DrawItems on it, the function to draw one item would be e.g. void Draw(DrawItem item);

    DrawItemCollection items = new DrawItemCollection();
    items.Add( ... all kinds of DrawItems ... );
    ...
    foreach (DrawItem item in items)
    Draw(item);

    Just to give a more concrete example to help you understand why one does something like that. You will find plenty of stuff like this for example for the Control class in System.Windows.Forms.


  • Understanding polymorphism parameter