Abstract classes in C# are a fundamental concept in object-oriented programming. An abstract class is a class that cannot be instantiated on its own, meaning you cannot create objects directly from it. Instead, it serves as a blueprint or template for other classes to derive from. Abstract classes provide a way to define common functionality that derived classes must implement while allowing each derived class to have its own specific implementation details.
Here are some key points about abstract classes in C#:
Declaration: An abstract class is declared using the abstract
keyword. It can include abstract methods, concrete methods, properties, and fields.
Abstract Methods: An abstract class may have abstract methods, which are declared without any implementation. These methods serve as placeholders that must be implemented in the derived classes.
Inheritance: Other classes can inherit from an abstract class using the class
keyword, and they must provide concrete implementations for all the abstract methods in the abstract class.
Instantiation: You cannot create instances of an abstract class using the new
keyword because it is incomplete and lacks concrete implementations for some methods.
Partial Abstraction: It is possible for a class to be partially abstract, containing both abstract and concrete methods. In such cases, the class is required to be marked as abstract.
Here's an example of how you can define an abstract class in C#:
abstract class Shape
{
// Abstract method to calculate the area.
public abstract double CalculateArea();
// Regular method that can be used by derived classes.
public void DisplayShapeType()
{
Console.WriteLine("This is a shape.");
}
}
In this example, Shape
is an abstract class that contains an abstract method CalculateArea()
and a regular method DisplayShapeType()
. The CalculateArea()
method does not have any implementation in the abstract class and is marked with the abstract
keyword. Any class that derives from Shape
must provide an implementation for CalculateArea()
.Here's how you can create a derived class that inherits from the abstract class:
class Circle : Shape
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
// Implementing the abstract method to calculate the area for the circle.
public override double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
In this case, the Circle
class derives from the Shape
abstract class and provides an implementation for the CalculateArea()
method specific to circles.Remember that you cannot create an instance of an abstract class directly. Instead, you can create instances of its derived classes. For example:
Circle circle = new Circle(5.0);
double area = circle.CalculateArea();
circle.DisplayShapeType();
This allows you to use the common methods and properties defined in the abstract class while leveraging the specific implementations in the derived classes.