Abstraction is one of the fundamental principles of object-oriented programming that focuses on hiding implementation details and exposing only the essential features of an object.
In C#, abstraction is achieved through abstract classes and interfaces.
his allows you to work with a simplified view of an object while hiding complex or irrelevant details.
This tutorial will cover:
1. Basics of Abstraction
Abstraction allows us to define an object by what it does rather than how it does it. For example, a Vehicle class can expose functionality like StartEngine and StopEngine without detailing the exact process for each specific vehicle type.
In C#, abstraction is implemented using:
- Abstract Classes: Classes that cannot be instantiated on their own and may contain both defined methods and abstract methods (methods without implementation).
- Interfaces: Define a contract that other classes must implement but do not provide any code implementation.
2. Abstract Classes
An abstract class provides a base for other classes to build upon. It cannot be instantiated directly. Abstract classes may contain both regular methods with implementation and abstract methods, which must be implemented by derived classes.
Syntax for Abstract Class:
public abstract class ClassName { // Abstract methods (no implementation) public abstract void MethodName(); // Regular methods with implementation public void RegularMethod() { // Code here } }
Example: Vehicle Abstract Class
using System; public abstract class Vehicle { public string Make { get; set; } public string Model { get; set; } public Vehicle(string make, string model) { Make = make; Model = model; } // Abstract method (must be implemented by derived classes) public abstract void StartEngine(); // Regular method public void DisplayInfo() { Console.WriteLine($"Vehicle: {Make} {Model}"); } } public class Car : Vehicle { public Car(string make, string model) : base(make, model) { } public override void StartEngine() { Console.WriteLine($"{Make} {Model} engine started with key."); } } public class Motorcycle : Vehicle { public Motorcycle(string make, string model) : base(make, model) { } public override void StartEngine() { Console.WriteLine($"{Make} {Model} engine started with button."); } } public class AbstractClassExample { public static void Main() { Vehicle myCar = new Car("Toyota", "Corolla"); Vehicle myMotorcycle = new Motorcycle("Honda", "CBR600"); myCar.DisplayInfo(); myCar.StartEngine(); myMotorcycle.DisplayInfo(); myMotorcycle.StartEngine(); } }
Explanation:
- The Vehicle class is an abstract class with an abstract method StartEngine.
- Car and Motorcycle are derived classes that implement StartEngine with their specific behavior.
- The DisplayInfo method in Vehicle provides shared functionality for both derived classes.
Output:
Vehicle: Toyota Corolla Toyota Corolla engine started with key. Vehicle: Honda CBR600 Honda CBR600 engine started with button.
3. Abstract Methods
Abstract methods are methods without any implementation in an abstract class. They must be overridden by any derived (non-abstract) class.
Example: Shape with Abstract Method
using System; public abstract class Shape { // Abstract method public abstract double GetArea(); public void Display() { Console.WriteLine("This is a shape."); } } public class Circle : Shape { private double radius; public Circle(double radius) { this.radius = radius; } public override double GetArea() { return Math.PI * radius * radius; } } public class Rectangle : Shape { private double width; private double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } public override double GetArea() { return width * height; } } public class AbstractMethodExample { public static void Main() { Shape circle = new Circle(5); Shape rectangle = new Rectangle(4, 6); Console.WriteLine("Circle area: " + circle.GetArea()); Console.WriteLine("Rectangle area: " + rectangle.GetArea()); } }
Explanation:
- The Shape class has an abstract method GetArea that each shape must implement.
- Circle and Rectangle provide specific implementations for GetArea, calculating the area based on their unique shapes.
Output:
Circle area: 78.53981633974483 Rectangle area: 24
4. Interfaces
An interface in C# is a contract that defines what methods or properties a class should implement, without providing any implementation details. Unlike abstract classes, interfaces can only contain method and property declarations (no fields or implementation).
Syntax for Interface:
public interface IInterfaceName { void MethodName(); }
Example: Payment System Using an Interface
using System; public interface IPayment { void ProcessPayment(double amount); } public class CreditCardPayment : IPayment { public void ProcessPayment(double amount) { Console.WriteLine($"Processing credit card payment of ${amount}"); } } public class PaypalPayment : IPayment { public void ProcessPayment(double amount) { Console.WriteLine($"Processing PayPal payment of ${amount}"); } } public class InterfaceExample { public static void Main() { IPayment payment1 = new CreditCardPayment(); IPayment payment2 = new PaypalPayment(); payment1.ProcessPayment(100.00); payment2.ProcessPayment(50.00); } }
Explanation:
- The IPayment interface defines a ProcessPayment method.
- Both CreditCardPayment and PaypalPayment implement IPayment, each with its unique implementation.
- By using interfaces, we can treat both classes as IPayment objects, providing flexibility in handling different payment types.
Output:
Processing credit card payment of $100 Processing PayPal payment of $50
5. Practical Examples of Abstraction
Example 1: Animal Abstract Class with Different Animals
This example uses an abstract class Animal to define common behavior for different types of animals.
using System; public abstract class Animal { public abstract void MakeSound(); public void Eat() { Console.WriteLine("The animal is eating."); } } public class Dog : Animal { public override void MakeSound() { Console.WriteLine("The dog barks."); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("The cat meows."); } } public class AnimalExample { public static void Main() { Animal dog = new Dog(); Animal cat = new Cat(); dog.MakeSound(); cat.MakeSound(); dog.Eat(); cat.Eat(); } }
Explanation:
- The Animal class has an abstract method MakeSound that each animal implements differently.
- The Eat method provides common functionality for all animals.
Output:
The dog barks. The cat meows. The animal is eating. The animal is eating.
Example 2: Appliance Interface for Home Appliances
This example uses an interface IAppliance to define common behavior for different types of home appliances.
using System; public interface IAppliance { void TurnOn(); void TurnOff(); } public class WashingMachine : IAppliance { public void TurnOn() { Console.WriteLine("Washing machine is now ON."); } public void TurnOff() { Console.WriteLine("Washing machine is now OFF."); } } public class Refrigerator : IAppliance { public void TurnOn() { Console.WriteLine("Refrigerator is now ON."); } public void TurnOff() { Console.WriteLine("Refrigerator is now OFF."); } } public class ApplianceExample { public static void Main() { IAppliance washingMachine = new WashingMachine(); IAppliance refrigerator = new Refrigerator(); washingMachine.TurnOn(); washingMachine.TurnOff(); refrigerator.TurnOn(); refrigerator.TurnOff(); } }
Explanation:
- The IAppliance interface defines methods that each appliance must implement.
- WashingMachine and Refrigerator classes implement the interface, providing specific behavior for turning on and off.
Output:
Washing machine is now ON. Washing machine is now OFF. Refrigerator is now ON. Refrigerator is now OFF.
Summary
Abstraction in C# helps in simplifying complex systems by defining clear interfaces or abstract classes, allowing details to be hidden and providing a generalized view of objects. Here’s a recap:
- Abstract Classes: Used for creating a base class with both defined and abstract methods. Derived classes must implement abstract methods.
- Abstract Methods: Declared in an abstract class and implemented by derived classes.
- Interfaces: Define a contract that any implementing class must fulfill without providing any implementation details.
- Practical Applications: Abstraction can simplify complex systems such as payment processing, appliance management, or animal behavior by focusing on essential characteristics.
Abstraction in C# improves modularity, reusability, and readability by allowing developers to hide unnecessary details and work with high-level object interfaces.