Abstract, virtual and Polymorphism
Below we have an example of class abstraction and polymorphism in C# programming.
public abstract class Pie
{
public string Name { get; set; }
public List<string> Ingredients { get; set; }
public bool IsBaked { get; set; }
protected Pie(string name, List<string> ingredients) => (Name, Ingredients) = (name, ingredients);
public void StartCooking()
{
// Do not do anything if it is baked...
if (IsBaked) return;
// define action before...
BeforeStartCooking();
Console.WriteLine("Cooking the pie...");
// define action after...
AfterCooked();
}
protected virtual void BeforeStartCooking() { }
protected virtual void AfterCooked() { }
}
public class ApplePie : Pie
{
public string Smells { get; set; } = "Smells like Apple Pie!";
public ApplePie(string name, List<string> ingredients) : base(name, ingredients)
{
}
protected override void AfterCooked()
{
Console.WriteLine(Smells);
}
}
Here is the breakdown of each class:
Pie: This is an abstract class that serves as a base class for any specific type of pie. It has properties for Name, Ingredients, and IsBaked. It also has a constructor that is used to initialize the Name and Ingredients properties. It has a public StartCooking method that simulates the cooking process, executing a BeforeStartCooking method (that could be overridden in child classes), performing the main action of baking the pie (unless it's already baked), and then executing AfterCooked method (that could also be overridden in child classes). The methods BeforeStartCooking and AfterCooked are declared as virtual, which means they can be overridden in a derived class.
ApplePie: This is a derived class from Pie that represents a specific type of pie. It has an additional property Smells initialized with the string "Smells like Apple Pie!". It uses base constructor to initialize Name and Ingredients properties. Also, it overrides the AfterCooked method from the base class to provide custom behavior specific to ApplePie, which is writing the smell of the apple pie to the console after it's cooked.
Test it like:
var applePie = new AbstractAndVirtual.ApplePie("Nana's apple pie", new List<string> {"apples", "flour"});
applePie.StartCooking();
It will print:
Cooking the pie...
Smells like Apple Pie!
No files yet, migration hasn't completed yet!