Friday 5 June 2009

OOP Basic: Polymorphism

Polymorphism gives us the ultimate flexibility in extensibility which is a basis of OO programming. Understanding Polymorphism is crucial to any OO language professional. The benefit of polymorphism is that you don’t need to know the object’s class to execute the polymorphic behaviour. We use polymorphism to achieve the late binding. For example, you may have many classes in an application, each with its own save method. When the application is saved, each object knows the class it belongs to and automatically calls the correct save method.

using System;

namespace Polymorphism
{
class Shape
{
public virtual void draw()
{
Console.WriteLine("Draw shape....");
}
}

class Circle: Shape
{
public override void draw()
{
Console.WriteLine("Draw circle....");
}
}

class Triangle : Shape
{
public override void draw()
{
Console.WriteLine("Draw triangle....");
}
}

class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("Draw rectangle...");
}
}

class Create
{
public Shape CreateShape(string str)
{
Shape s;
switch (str)
{
case "c":
s = new Circle();
break;
case "r":
s = new Rectangle();
break;
case "t":
s = new Triangle();
break;
default:
s = new Shape();
break;
}
return s;
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please type a Shape class you want to create: ");
string strShape = Console.ReadLine();
Console.WriteLine("string is: {0}", strShape);

Create c = new Create();
Shape s = c.CreateShape(strShape);
s.draw();
Console.ReadLine();
}
}
}

In the above example, if we want to add a new class to draw Oval shape, we will have a class like:

class Oval: Shape
{
public override void draw()
{
Console.WriteLine("Draw oval....");
}
}

We want to be able to ‘plug-in’ this class into our application without having to make any code changes in the original code and call the draw() of Oval class during run time. By using Polymorphism, the only place we need to make the change is our Create method and we leave our client application code untouched.

Understanding polymorphism is key to designing scalable, plug-and-play architecture application.

No comments:

Post a Comment