Explain abstract class in c# with example
An abstract class in C# is a class that cannot be instantiated on its own and is meant to serve as a base or template for other classes. It may contain abstract (unimplemented) methods and properties that must be implemented by derived classes. Here's a simple example:
```csharp
using System;
// Define an abstract class
abstract class Shape
{
// Abstract method to calculate area (must be implemented by derived classes)
public abstract double CalculateArea();
// Regular method
public void Display()
{
Console.WriteLine("This is a shape.");
}
}
// Derived class 1: Circle
class Circle : Shape
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
public override double CalculateArea()
{
return Math.PI * Math.Pow(Radius, 2);
}
}
// Derived class 2: Rectangle
class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
public override double CalculateArea()
{
return Width * Height;
}
}
class Program
{
static void Main()
{
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);
circle.Display();
Console.WriteLine("Circle Area: " + circle.CalculateArea());
rectangle.Display();
Console.WriteLine("Rectangle Area: " + rectangle.CalculateArea());
}
}
```
In this example, the `Shape` class is abstract and defines an abstract method `CalculateArea()`. The `Circle` and `Rectangle` classes inherit from `Shape` and provide their own implementations of the `CalculateArea()` method. The `Display()` method is a regular method that can be shared among all derived classes.
You cannot create an instance of the `Shape` class, but you can create instances of its derived classes (`Circle` and `Rectangle`) and call their methods. This allows you to define a common interface for shapes while providing flexibility for individual shape types to implement their specific behaviors.
Comments
Post a Comment