harrylmh said:
Hi,
I'm learning C# and I just don't quite understand the need for
polymorphism. why do we need to use it? how does a base class variable
holding a derived class instance do any good?
Also, what's the difference between method hiding and overriding when
they're both still overriding the base method.
Thanks
Polymorphism allows you to treat instances of different classes in a uniform
manner. Suppose e.g., that you have a container of objects that are all
subclasses of the type Drawable, say Rectangles and Circles. Suppose also
that class Drawable contains a virtual method Draw that the subclasses
override. You can then draw all the objects on the screen with code like
this:
foreach (Drawable d in drawables)
d.Draw(graphics);
The real power of this approach comes from its extensibility. You can add a
completely new Drawable subtypes and your loop above would work without you
having to change it. Compare that to the C-style code where you would have a
switch on object type and call to a specific drawing function based on the
type. You would have to update this switch statement every time a new class
was introduced - this would be a maintenance problem.
Method hiding, on the other hand, is something that actually breaks
polymorphism. If one of you Drawable subclasses would declare a new Draw
method like so:
public new void Draw(Graphics g)
{
//...
}
Then the loop above would end up calling Drawable.Draw for instances of this
type. In general this is something that you don't want to happen.
Regards,
Sami