I am learning OOP and have a question about what is exactly happening with the code below.
I have the classic Dog Animal example going. Dog inherits Animal.
public class Animal
{
public string Name { get; set; }
public virtual string Speak()
{
return "Animal Speak";
}
public string Hungry()
{
return this.Speak();
}
}
public class Dog : Animal
{
public override string Speak()
{
return "Dog Speak";
}
public string Fetch()
{
return "Fetch";
}
}
Both questions are based on this assignment: Animal a = new Dog();
- What is actually happening when I declare an
Animaland set it to aDogreference. Is there a specific term for this? - When I call
a.Hungry(), the output is “Dog Speak.” If the output is “Dog Speak”, why can I not calla.Fetch()? What is the term for what’s happening here?
Any help and further reading on the particular topic would be greatly appreciated.
Dogas if it were anAnimal. (Thanks to Matt Burland for reminding me that this is the appropriate term.)Animal, and as such you can only access members that the compiler knows anAnimalcan access, i.e.SpeakandHungry. It doesn’t know that theAnimalis aDog, so it can’t callFetch. The variable would need to be of typeDogfor you to be able to callFetchon it.