One doesn't inherit from Two, and that is what is not working great.
Class inheritance doesn't mean to hide or to replace one class's property value, but that the derived class is a specialization of the base class it inherits from.
For example:
public class Cat {
}
public class Dog {
}
What do these two have in common?
- They have four legs;
- They are all animals;
- They have hairs;
What do they not have in common?
- A cat meows;
- A dog barkles;
Let's revise our model by setting this in order.
public class Cat {
public bool HasHair { get { return true; } }
public int Legs { get { return 4; } }
public string Speaks { get { return "Meows"; } }
}
public class Dog {
public bool HasHair { get {return true; } }
public int Legs { get { return 4; } }
public string Speaks { get { return "Barkles"; } }
}
Now, to save you time and coding, what could we do? Generalize what both classes have in common? Alright! But how to make it so!?
public class Animal {
public bool HasHair { get { return true; } }
public int Legs { get { return 4; } }
public virtual string Speaks { get { return "Does a sound"; } }
}
// We can now inherit from Animal to write our Cat and Dog classes.
public class Cat : Animal {
public overrides string Speaks { get { return "Meows"; } }
}
public class Dog : Animal {
public overrides string Speaks { get { return "Barkles"; } }
}
And you can do:
Dog dog = new Dog();
dog.Legs; // Because Legs is an Animal property, and a Dog inherits from Animal, then Dog has a property called Legs, since it got it from his base class.
Now, we can do:
Animal pet = (Animal)(new Cat());
That said, you can typecast a Cat to an Animal, because it is an Animal! Now, you have to consider that your typecasted Cat will "do a sound", instead of "meowling", since by typecasting Cat to Animal, you're saying that you want to work with any Animal, as long as it is one. So both Cat and Dog are animals.
We could push our example even further by saying that not every animal has four legs, some doesn't have any, and others have only two. Then, we would have to generalize and to specialize accordingly.