What is polymorphism, and how is it implemented?
Polymorphism is one of
the pillars of any object oriented programming language. Polymorphism enables us
to write applications that process objects that share the same base class
heirarchy as if they are all objects of the base class. With Polymorphism, the
same method name and signature can be used to cause different actions to occur
depending on the type of the object on which the method is invoked.
Ex:
public class Shape
{
public abstract double
GetArea();
}
public class Rectangle : Shape
{
public override
double GetArea()
{
return width * length;
}
}
public class
Square : Shape
{
public override double GetArea()
{
return side *
side;
}
}
In the above example, the user can take any shape object
instance and call GetArea() method. Depending on the type of the object, the
specific GetArea() is called and appropriate value is returned. Note all the
methods (GetArea()) has the exact signature including the return type.
No comments:
Post a Comment