Suppose we have declared these two classes:
public class Animal
{
//.....
}
public class Dog : Animal
{
//.....
}
Well, my question is: why below line of code is valid?
Animal animal = new Dog();
EDIT:
In e-book, “Professional C# 2008”, there is a paragraph that says:
It’s always safe to store a derived type within a base class reference.
You are creating a new
Dog, but then you are treating (using) it as anAnimal.This is especially useful when you want to have some behaviour that is owned or exposed by the
Animal, but theDogmay then override that with something different. TheDogcan be used as either aDogor as anAnimal, 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:
Notice two things here:
Animalclass had to override theMove()function, because in my base class i made the decision that all animals should have aMove(), but i didn’t specify how they should move – that is up to the individual animal to specifyCaveManclass didn’t override theMakeSignatureSound()function, because it had already been defined in the base class and it was adequate for himNow if i do this:
i will get this on the console:
But because i used an abstract base class, i cannot instantiate an instance of it directly, i can’t do this:
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 pureAnimalthat had no behavior or characteristics.