Abstract classes are very useful when you need to represent many similar things in the usual way.
For example, say you wanted to represent the zoo in code, and you had to get a list of products to make sure you have the right food. How do you imagine your favorite food for all your animals? And what noise does everyone make? How about how they move? You can try to use a superclass to store large lists of products, noises and movements, but itโs easier to have a common definition for an Animal, and then each animal provides its own implementation details:
public class Zoo { public Animals[] AnimalsInZoo { get; set;} public List<Food> GetGroceryList(){ List<Food> groceries = new List<Food>(); foreach(Animal a in Animals[]){ groceries.Add(a.FavoriteFood); } return groceries; } public void MakeAnimalsSing(){ foreach(Animal a in Animals[]){ a.MakeNoise(); } } }
An abstract class of animals will look like this:
public abstract class Animal { public abstract void MakeNoise(); public abstract Food FavoriteFood { get; } public abstract void Move(); }
And let's say there were two kinds of animals in the zoo:
public class Panda : Animal{ public override void MakeNoise(){
Having a common abstract class, I can easily work with any number of different types of animals, not knowing who I work with, but everyone can behave differently.
A superclass simply cannot provide flexibility or detail.
source share