C# Abstract Classes: Achieving Abstraction and Polymorphism
Understand abstract classes in C# and their role in achieving abstraction and polymorphism. This tutorial explains abstract methods, their relationship with derived classes, and how abstract classes enforce contracts and promote flexible, maintainable object-oriented designs.
Understanding Abstract Classes in C#
What is an Abstract Class?
In C#, an abstract class is a class that cannot be instantiated directly; it serves as a base class for other classes (derived classes). Abstract classes are used to achieve *abstraction*, a core principle of object-oriented programming where you focus on *what* an object does rather than *how* it does it. Abstract classes can contain both abstract methods (methods without implementations) and concrete methods (methods with implementations). Derived classes must provide implementations for any abstract methods inherited from the abstract class.
Abstract Methods
An abstract method is a method declared without a body. It's a placeholder for functionality that must be implemented by derived classes. Abstract methods enforce a contract: any class inheriting from the abstract class must provide its own implementation of the abstract method.
Example: Abstract Method Declaration
public abstract void Draw();
Note: You cannot use `static` or `virtual` modifiers with abstract methods. Abstract methods are implicitly virtual; they can be overridden by derived classes.
Example: Abstract Class and Inheritance
This example shows an abstract `Shape` class with an abstract `Draw()` method. Two derived classes, `Rectangle` and `Circle`, provide specific implementations for `Draw()`. This demonstrates the concept of polymorphism where different classes provide their own specific implementation of a base method.
C# Code
using System;
public abstract class Shape {
public abstract void Draw();
}
public class Rectangle : Shape {
public override void Draw() { Console.WriteLine("Drawing rectangle..."); }
}
public class Circle : Shape {
public override void Draw() { Console.WriteLine("Drawing circle..."); }
}
public class Test {
public static void Main(string[] args) {
Shape s = new Rectangle();
s.Draw();
s = new Circle();
s.Draw();
}
}
Conclusion
Abstract classes are a key part of object-oriented programming in C#. They promote code reusability, abstraction, and polymorphism, enabling you to design flexible and extensible applications.