What is ?
It let invoke methods of the class through of a reference class base during a run-time. This is useful when you have a array and you have to invoke each method of him. they don’t need be the same type of the object.
using System;
public class DrawingObject
{
public virtual void Draw();
{
Console.WriteLine(“I’m just a generic drawing object.”);
}
}
This will be the base for others objects of classes inherit. The method Draw() performs the only action of print the declaration.
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.”);
}
}
Show 3 classes, and this classes are inherited the DrawingObject. Each class have a method Draw() and each Draw() have a modifier override.
using System;
public class DrawDemo
{
public static int Main( )
{
DrawingObject[] dObj = new DrawingObject[4];
dObj[0] = new Line();
dObj[1] = new Circle();
dObj[2] = new Square();
dObj[3] = new DrawingObject();
foreach (DrawingObject drawObj in dObj)
{
drawObj.Draw();
}
return 0;
}
}
This program implements polimorphism. In the method Main() of class DrawDemo, there is a range wich are being created. The type of the object in this matrix is a DrawingObject class. The matrix is called dObj and is being initialized for stop four objects of type DrawingObject.
Output:
I’m a Line.
I’m a Circle.
I’m a Square.
I’m just a generic drawing object.
The override method Draw() of each derived performs how shown on the program DrawDemo. The las line is starting of virtual Draw() DrawingObject method of the class. This, because the real run-time type of fourth element was an array DrawingObject object.
So, this is only a summary about polimorphism in C#. Hope this help every one to start use this resource.
Font: http://www.oficinadanet.com.br/artigo/885/curso_de_c_sharp_licao_9_polimorfismo
One thought on “Polymorphism – C#”