Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, September 22, 2015 3:05 PM
The below program is compile time polymosphism but how can run time be achieved using array of interface types.
If wrong can someone please tell me the changes to implement Array of Interface Types using runtime polymorphism
public interface IPointy
{
byte GetNumberOfPoints(); // Implicitly public and abstract.
void Draw();
}
public class Hexagon : IPointy
{
public Hexagon() { }
public Hexagon(string name) { }
public void Draw()
{
// IPointy Implementation.
Console.WriteLine("");
Console.WriteLine("Drawing the Hexagon");
}
// IPointy Implementation.
public byte GetNumberOfPoints() { return 6; }
}
public class Triangle : IPointy
{
public Triangle() { }
public Triangle(string name) { }
public void Draw()
{
// IPointy Implementation.
Console.WriteLine("");
Console.WriteLine("Drawing the Triangle");
}
public byte GetNumberOfPoints()
{
// IPointy Implementation.
return 3;
}
}
class ArrayExample
{
static void Main(string[] args)
{
Console.WriteLine("Demonstrating arrays of interfaces");
IPointy[] obj = { new Triangle("Triangle"), new Hexagon("Hexagon"), new Triangle() };
int i = 0;
foreach (IPointy I in obj)
{
I.Draw();
Console.WriteLine("Number of Points are {0}\n", I.GetNumberOfPoints());
}
Console.ReadLine();
}
}
All replies (3)
Tuesday, September 22, 2015 3:29 PM ✅Answered
I would say that this is run-time polymorphism. The compiler doesn't necessarily know what is in the array, only at run-time would it decide which of the IPoint.Draw() implementations it needs to call.
In your example you have hard-coded your array, but to see what I mean consider the fact that you could dynamically build your array (or List) depending on user input for example.
Tuesday, September 22, 2015 3:58 PM ✅Answered
You aren't using compile time polymorphism at all here. You're using runtime poly. CTP, as generally defined in academic circles, is swapping out implementations at compile time. The common example of this in an OOP language is method overloading. It is the compiler that decides what method to call.
public class Foo
{
public void Bar ( int x ) { }
public void Bar ( double x ) { }
public void Bar ( string x ) { }
}
//Later
var f = new Foo();
f.Bar(10); //Compiler decides...
f.Bar("Hello"); //Compiler decides
RTP is when the runtime determines which to call, method overriding in academic. This pretty much mandates the use of virtual methods, of which interfaces is a special case. Hence your example is RTP and not CTP.
Michael Taylor
http://blogs.msmvps.com/p3net
Tuesday, September 22, 2015 4:32 PM
Thanks RJP1973 abnd CoolDadTx for the reply...