Thursday, September 3, 2009

Polymorphism

Polymorphism allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods.

USAGE
The virtual modifier indicates to derived classes that they can override this method.

The override modifier allows a method to override the virtual method of its base class at run-time. The override will happen only if the class is referenced through a base class reference.

The new modifier allows you to add a member/method that already exists in the base class to the sub class, without overriding the parent member/method.
This means that if you create a subclass object with method Test(), but reference it through a base class reference, the base class method Test() will be called.
If you create a subclass object and reference it through a subclass object reference, the new Test() method will be called.

BASE CLASS

public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I'm just a generic drawing object.");
}
}

DERIVED CLASSES

using System;

public class Line : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Line.");
}
}

public
class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Circle.");
}
}

public
class Square : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Square.");
}
}

public class SpecialSquare : DrawingObject
{
public new void Draw()
{
Console.WriteLine("I'm a Special Square.");
}
}


EXAMPLE PROGRAM

DrawingObject[] dObj = new DrawingObject[54];

dObj[0] =
new Line();
dObj[1] =
new Circle();
dObj[2] =
new Square();
dObj[3] =
new DrawingObject();
dObj[4] = new SpecialSquare();

Console.WriteLine("1");


foreach (DrawingObject drawObj in dObj)
{
drawObj.Draw();
}

Console.WriteLine("2");

Line line = new Line();

Square square = new Square();

SpecialSquare specialSquare = new SpecialSquare();

line.Draw();

square.Draw();

specialSquare.Draw();

PROGRAM OUTPUT

1
I'm a Line.
I'm a Circle.
I'm a Square.
I'm just a generic drawing object.
I'm just a generic drawing object. THE NEW MODIFIER MEANS WILL USE BASE CLASS METHOD
2
I'm a Line.
I'm a Square.
I'm a Special Square.