Interfaces executing Polymorphic Traits
Example of Dynamic Polymorphism using interfaces as
base class.
overriding the base class abstract method in derived classes .
Parent array is pointing to the instances array of derived classes.
The corresponding Method is executed and that is determined during runtime by the interfaces .
That interfaces also coded as base type to derived classes.
Also the code explains the explicit interface implementation in derived classes .
Interfaces are implemented in derived classes.
The Derived class is also inheriting from base class.
if we create an array of base class pointing to derived class instances.
Interfaces do execute polymorphic traits and executes its own member function from the derived class instances from the base class array objects .
CLR determines Interface Methods during Runtime and executes the method appropriately.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InterF2
{
class Program
{
static void Main(string[] args)
{
shape[] s = { new Triange("Tri1"), new Hexagon("Hex1"), new Test("Test1"), new Hexagon("Hex2") };
Console.WriteLine();
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine("class Draw function for the Array");
s[i].Draw();
if (s[i] is IDraw)
{
IDraw dr = s[i] as IDraw;
Console.WriteLine("Interface Draw function for the Array");
Console.WriteLine();
dr.Draw();
Console.WriteLine("No of Points for interface implementation {0}", dr.GetPoints());
}
Console.WriteLine("........................................................");
}
Console.ReadLine();
}
}
public class Hexagon : shape, IDraw
{
public Hexagon(string s)
: base(s)
{
}
public override void Draw()
{
Console.WriteLine("Hexagon class and name is {0}", sname);
}
public byte GetPoints()
{
return 6;
}
}
public class Triange : shape, IDraw
{
public Triange(string s)
: base(s)
{
}
public override void Draw()
{
Console.WriteLine("The Triangle class Name is {0}", sname);
}
public byte GetPoints()
{
return 3;
}
}
public abstract class shape
{
public string sname;
public shape(string s)
{
sname = s;
}
public abstract void Draw();
}
public interface IDraw
{
void Draw();
byte GetPoints();
}
public class Test :shape ,IDraw
{
public Test(string s)
: base(s)
{
}
public override void Draw()
{
Console.WriteLine("The Name of the shape is {0}", sname);
}
void IDraw.Draw()
{
Console.WriteLine("IDraw interface is Drawn");
}
public byte GetPoints()
{
return 0;
}
}
}
Reference: http://rsan1234.blogspot.com