I am new to C# and wanted to ask few questions about Polymorphism so I thought I would continue on from this thread.
I have read up on polymorphism.
Let's say I have a parent class called Animal and a child class called Dog. Dog inherits Animal. So like this:
using System;
namespace Polymorphism
{
class Animal
{
public string FirstName = "FN";
public string LastName = "LN";
public void [COLOR=#0000ff]DisplayFullName[/COLOR]()
{
Console.WriteLine(FirstName + " " + LastName);
}
}
class Dog : Animal
{
public void [COLOR=#0000ff]DisplayFullName[/COLOR]()
{
Console.WriteLine(FirstName + " " + LastName + " - [COLOR=#ff0000]Woof[/COLOR]");
}
}
class Program
{
static void Main()
{
Animal a = new Dog();
a.DisplayFullName();
}
}
}
Now from what I understand, Polymorphism allows you to declare a Parent class reference variable that is able to point to a Child class object i.e. Animal
a = new Dog().
I am also aware that during run time, the variable changes it's type i.e. the variable
a changes from Animal to Dog or does it change from Dog to Animal? I am not too sure.
I am also convinced that this (i.e. at run time data changes) only if we use the keywords "virtual" (in the parent class method called
DisplayFullName()) and "override" (in the child class method called
DisplayFullName()). I have purposely left these keywords out in my code above so that it invokes the Parent class method and not the child class method. Does that mean that during that particular run time, no implicit data conversion happened for the variable
a? And if so, does that mean a remained as an Animal type throughout?
Now, things change when I used the keywords "virtual" and "override". Lets imagine I add these words into my code above. Now, does this cause the variable
a to change t data type during run time? If so, am I correct in saying "during runtime, variable
a changes from an Animal type to a Dog type?