Abstract class in C# example with program – An abstract class can have both abstract method that is unimplemented method without body and methods with implementation.
Recommended to read C# abstract method with example .
Note that abstract methods has no body and have only declaration in the class and will be implemented by its derived classes.
Below is a pseudo real time of implementation of an abstract class for a Vending Machine that will deliver Tea and Coffee.
The common methods milk(), hotWater(), and addSugar() will be defined and provided by abstract class.
The abstract method ingredient() will be introduced in the abstract class itself that is unimplemented, and will be implemented by derived classes e.g. Tea and coffee etc. so, they can add tea or coffee depends upon their choice.
/*
* Abstract class in C#
*
*/
//have some common method in base class and force subclasses to implement it
//Vending machine - TEA, COFFEE
//Abstract base class - cannot create an object of abstract class
abstract class Beverages {
private void milk() {
Console.WriteLine("Hot Milk");
}
private void hotWater() {
Console.WriteLine("Hot water");
}
private void addSugar() {
Console.WriteLine("Hot Suger");
}
public void addBasicElements() {
milk();
hotWater();
addSugar();
}
//abstract method that will be implemented by derived classes
public abstract void ingredient();
}
class Tea : Beverages {
public override void ingredient() {
Console.WriteLine("Add Tea");
}
}
class Coffee : Beverages {
public override void ingredient()
{
Console.WriteLine("Add Coffee");
}
}
class Expresso : Beverages {
public override void ingredient()
{
Console.WriteLine("Add Expresso");
}
}
public class VendingMachine {
public static void Main(String[] args) {
// prepare tea
Beverages t = new Tea();
t.addBasicElements();
t.ingredient();
// prepare coffee
Beverages c = new Coffee();
c.addBasicElements();
c.ingredient();
// prepare expresso
Beverages e = new Expresso();
e.addBasicElements();
e.ingredient();
}
}
Output:
Hot Milk
Hot water
Hot Suger
Add Tea
Hot Milk
Hot water
Hot Suger
Add Coffee
Hot Milk
Hot water
Hot Suger
Add Expresso