You are creating a new Dog
, but then you are treating (using) it as an Animal
.
This is especially useful when you want to have some behaviour that is owned or exposed by the Animal
, but the Dog
may then override that with something different. The Dog
can be used as either a Dog
or as an Animal
, because it is both.
Edit: here is a quick example, and i'm going to use an abstract base class so you can see the real value of this arrangement:
public abstract class Animal
{
public abstract void Move();
public virtual void MakeSignatureSound()
{
Console.WriteLine("Ugggg");
}
}
public class Dog : Animal
{
public override void Move()
{
RunLikeAPuppy();
}
public override void MakeSignatureSound()
{
Console.WriteLine("Woof");
}
}
public class CaveMan : Animal
{
public override void Move()
{
RunLikeANeanderthal();
}
}
public class Cat : Animal
{
public override void Move()
{
RunLikeAKitteh();
}
public override void MakeSignatureSound()
{
Console.WriteLine("Meioww");
}
}
Notice two things here:
- all three derivatives from the
Animal
class had to override the Move()
function, because in my base class i made the decision that all animals should have a Move()
, but i didn't specify how they should move - that is up to the individual animal to specify
- the
CaveMan
class didn't override the MakeSignatureSound()
function, because it had already been defined in the base class and it was adequate for him
Now if i do this:
Animal caveman = new CaveMan();
Animal dog = new Dog();
caveman.MakeSignatureSound();
dog.MakeSignatureSound();
i will get this on the console:
Ugggg
Woof
But because i used an abstract base class, i cannot instantiate an instance of it directly, i can't do this:
Animal animal = new Animal();
As a developer, i want to ensure that when others (or myself) create a new Animal
, it has to be a specific type, not just a pure Animal
that had no behavior or characteristics.