Mark As Completed Discussion

Abstraction

In object-oriented programming, abstraction is the process of simplifying complex systems by breaking them down into smaller, more manageable parts. It allows us to focus on the essential features and hide unnecessary details.

In C#, abstraction is achieved through abstract classes and interfaces.

Abstract Classes

An abstract class is a class that cannot be instantiated and serves as a base for other classes. It can contain a combination of abstract and non-abstract (concrete) methods, properties, fields, and events. Abstract methods are declared without an implementation and must be overridden in derived classes.

Here's an example of an abstract class Shape that defines a common method GetArea() for calculating the area of different shapes:

TEXT/X-CSHARP
1public abstract class Shape
2{
3    public abstract double GetArea();
4}

Derived classes, such as Circle and Rectangle, can inherit from the abstract class Shape and provide their own implementation for the GetArea() method:

TEXT/X-CSHARP
1public class Circle : Shape
2{
3    private double radius;
4
5    public Circle(double radius)
6    {
7        this.radius = radius;
8    }
9
10    public override double GetArea()
11    {
12        return Math.PI * radius * radius;
13    }
14}
15
16public class Rectangle : Shape
17{
18    private double length;
19    private double width;
20
21    public Rectangle(double length, double width)
22    {
23        this.length = length;
24        this.width = width;
25    }
26
27    public override double GetArea()
28    {
29        return length * width;
30    }
31}

In the Main() method, we can create instances of the derived classes and call the GetArea() method to calculate their areas:

TEXT/X-CSHARP
1Shape circle = new Circle(5);
2Shape rectangle = new Rectangle(4, 6);
3
4Console.WriteLine("Area of Circle: " + circle.GetArea());
5Console.WriteLine("Area of Rectangle: " + rectangle.GetArea());
C#
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment