Understanding Abstraction in C#

Understanding Abstraction

Welcome back! Previously, you delved into polymorphism and learned how to create more flexible code structures using classes and inheritance. In this session, we will explore a crucial aspect of Object-Oriented Programming in C#: abstract classes and abstract methods.

What is an Abstract Class?

An abstract class in C# is a class that cannot be instantiated directly. Think of it as a blueprint for other classes. It can include abstract methods that are declared without implementation and non-abstract methods that have implementation. However, an abstract class can also be entirely free of methods initially.

To illustrate this, let's create an abstract class using the abstract keyword:

// Defining an abstract class
public abstract class Shape
{
    // ...
}

This Shape class serves as a blueprint. Subclasses can inherit from Shape and add specific attributes and behaviors.

Implementing Abstract Methods

Now that you understand what an abstract class is, let's add abstract methods to our Shape class. An abstract method acts as a placeholder without any implementation, serving as a rule that subclasses must follow. It enforces consistency across subclasses while allowing each to fulfill the required behavior uniquely.

public abstract class Shape
{
    // Defining abstract methods
    public abstract double Area();
    public abstract double Perimeter();
}

Subclasses of Shape must implement these abstract methods.

Concrete Class: Circle

To see abstract methods in action, let's create a concrete class called Circle that inherits from Shape. The Circle class uses its constructor to initialize the radius and overrides both methods to provide specific implementations for calculating its area and perimeter.

public class Circle : Shape
{
    public double Radius { get; set; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    // Overridden method to calculate the area of the circle
    public override double Area()
    {
        return Math.PI * Math.Pow(Radius, 2);
    }

    // Overridden method to calculate the perimeter of the circle
    public override double Perimeter()
    {
        return 2 * Math.PI * Radius;
    }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal