Abstract classes are a fundamental concept in C# and object-oriented programming. They serve as a blueprint for other classes, providing a common structure and behavior while allowing for specialized implementations.
An abstract class is a special type of class that cannot be instantiated directly. It's designed to be inherited by other classes, known as concrete classes. Abstract classes can contain both abstract and non-abstract members.
To declare an abstract class in C#, use the abstract
keyword before the class definition. Here's a basic example:
public abstract class Shape
{
public abstract double CalculateArea();
public void Display()
{
Console.WriteLine($"Area: {CalculateArea()}");
}
}
In this example, Shape
is an abstract class with an abstract method CalculateArea()
and a concrete method Display()
.
To use an abstract class, you must create a derived class that implements all abstract members. Here's an example:
public class Circle : Shape
{
private double radius;
public Circle(double r)
{
radius = r;
}
public override double CalculateArea()
{
return Math.PI * radius * radius;
}
}
The Circle
class inherits from Shape
and provides an implementation for the abstract CalculateArea()
method.
Abstract classes are useful in several scenarios:
While abstract classes and C# Interfaces serve similar purposes, they have key differences:
Abstract Classes | Interfaces |
---|---|
Can have implementation details | Only method signatures (prior to C# 8.0) |
Support single inheritance | Support multiple inheritance |
Can have constructors | Cannot have constructors |
override
keywordAbstract classes play a crucial role in C# Inheritance and Polymorphism. They provide a powerful way to design flexible and extensible class hierarchies in your C# applications.