On Fri, 25 May 2007 11:13:51 -0700, weird0 <am********@gmail.comwrote:
Can anyone explain briefly what is the difference between inheritance
and polymorphism?
Briefly? Heh...okay. I'll try.
Inheritance: when one object inherits functionality implemented by
another. This allows you to create new objects that share base
functionality with other objects, while implementing their own new,
additional functionality.
As an example: in .NET, all classes derived from Control inherit the
Control.Text property. They don't need to implement that property
themselves, as it exists in the base class and is already done for them.
Polymorphism: when functionality defined in some base object can vary in
implementation depending on the actual object instance and what derived
class it actually is. This allows you to create base objects that define
and even implement a basic contract (or "interface") but allow derived
classes to change the way that contract is implemented.
As an example: in .NET all classes derived from Control inherit the
OnPaint() method. They only have to implement a new vesion of that method
if they want to draw differently from the base class, but more importantly
*if they do implement a new version of that method*, then a caller with a
reference to that class does not need to know that it's the derived
class. It can call the base Control.OnPaint() method via a Control-typed
reference (eg "Control ctl; ctl.OnPaint()") and the derived class's
implementation will still be the one that's called (or via any other base
class in the inheritance chain for that instance, for that matter).
As a more concrete example of the above: let's suppose you wanted to
inherit from the PictureBox class, and you wanted to take advantage of the
PictureBox's OnPaint implementation, but add to that a line drawn
diagonally through the image. You could create a new class that inherits
from PictureBox, and which implements a new OnPaint() method that simply
calls the base OnPaint() method, and then draws a diagonal line across the
control. In this case, you are taking advantage of both inheritance of an
implementation as well as the polymorphism of the base Control class.
You might as well ask about interfaces too. :) They are like abstract
classes in C++, where you would have one or more virtual methods without
an implementation ("pure virtual"), requiring all inheritors to implement
the method. The main difference being that an interface cannot have any
implementation defined in it, while a C# class cannot have "pure virtual"
methods. C# makes a clear delineation between the two, while C++ allows
you to have an abstract class that still implements some functionality.
Pete