Reputation: 119
polymorphism example:
public class animal
{
public void virtual speak()
{
Console.WriteLine("Animals can speak in many ways.");
}
}
public class dog : animal
{
public void override speak()
{
Console.WriteLine("I bark!");
}
}
static void main()
{
animal doggy = new dog();
doggy.speak();
}
output:
I bark!
I keep reading that the correct speak method is called during runtime, but is it not already hard coded and does the compiler not recognize which method it will invoke based on the virtual and override keywords?
Upvotes: 0
Views: 81
Reputation: 124642
Your compiler doesn't necessarily know which implementation will be the underlying type. Take, for example:
class A
{
public virtual void F() { Console.WriteLine("A"); }
}
class B : A
{
public override void F() { Console.WriteLine("B"); }
}
class Program
{
static A GetImpl(int i)
{
switch(i)
{
case 1:
return new A();
case 2:
return new B();
default:
// whatever
}
}
static void Main(string[] args)
{
var i = int.Parse(Console.ReadLine());
A a = GetImpl(i);
a.F();
}
}
How could the compiler possibly know if an A
or a B
is returned? It cannot, so the task of calling the correct method is delegated to the runtime.
Upvotes: 3
Reputation: 29265
If your code was something like
Animal anAnimal= NoahsArc.getNextAnimal();
anAnimal.speak();
Now you don't actually know what sort of animal you are going to get, so the runtime ensures the correct speak
method is called.
Upvotes: 1