How to Use Abstract Classes and Methods in C# Application

How to Use Abstract Classes and Abstract Methods in C# Application

In this article, I am going to discuss How to Use Abstract Classes and Abstract Methods in C# Application Development with Examples. Please read our previous article where we discussed Abstract Classes and Abstract Methods in C#. In the previous article, we discussed what are abstract methods and abstract classes and the rules to use them. In this article, I will show you how to use abstract classes and abstract methods in our applications.

What are Abstract Classes and Abstract Methods in C#:
  1. Abstract Method: A method without a body is known as an abstract method.
  2. Abstract Class: A class that contains any abstract members in it is known as an abstract class.

A class that is declared by using the keyword abstract is called an abstract class. An abstract class is a partially implemented class used for implementing some of the methods of an object which are common for all next-level subclasses and the remaining abstract methods to be implemented by the next-level subclasses. So, it contains both abstract methods and concrete methods including variables, properties, and constructors.

How to Use Abstract Classes and Abstract Methods in C#?

We have already discussed how to use Inheritance in our Application Development. If you have not read that article, please read that article by clicking on the below link.

How to use Inheritance in Application Development

We discussed that Application Development is all about dealing with Entities. And every entity is going to have a set of Attributes. And we just need to identify the common attributes and we need to put them in a hierarchical order. So, exactly the same thing we will try to understand now with abstract classes and abstract methods. Because when we are using abstract classes means we are going to use Inheritance otherwise there is no use of Abstract classes.

The concepts of abstract methods and abstract classes are an extension to the inheritance wherein inheritance we have been discussing that with the help of a parent class we can provide property to the child class that can be consumed by the child classes which gives us re-usability.

Along with the parent providing property to the children, the parent can also impose the restriction on the children with the help of abstract methods so that all the child classes have to full fill the restriction without failing.

Real-Time Example to Understand Abstract Classes and Methods in C#:

We are going to develop an application for calculating the Area of Rectangle, Circle, Triangle, and Cone. So, for our application, the followings are going to be our entities.

Entities: Rectangle, Circle, Triangle, Cone.

Next, what do we need to do once we identify the Entities for our application? Next, we need to identify the attributes of each and every entity as follows.

Rectangle: Height and Width
Circle: Radius and PI
Triangle: Width (also called Base) and Height
Cone: Radius, Height, and PI

So, these are the Entities and their attributes. Next, we need to identify the common attributes. Why do we need to identify the common attributes? Because if we put the common attributes in each and every class, then code duplication comes into the picture. And object-oriented programming is mainly used for re-usability, not for code duplication. If you want more clarify why need to identify common attributes, please read our How to use Inheritance in Application Development article.

So, today in our application we have four shapes, tomorrow might be some new shapes comes like Polygon, Square, Rhombus, etc. So, the common attributes in our case, Height, Width, Radius, and PI may be used in those shapes as well. So, we need to identify the common attributes of each and every entity.

So, what we need to do is, first we need to define one class, let’s say Shape with all these common attributes as follows. This is the first step in application development.

public class Shape
{
    public double Height;
    public double Width;
    public double Radius;
    public const float PI = 3.14f;
}

Now, if I make this class Shape as the Parent class for the rest of the four classes i.e. Rectangle, Circle, Triangle, and Cone, then we don’t need to declare the above attributes in those classes. We can directly use them. For example, if we create the classes like below, then all the classes will contain all the properties.

public class Rectangle : Shape
{
    //Contain All the Attributes
}
public class Circle : Shape
{
    //Contain All the Attributes
}
public class Triangle : Shape
{
    //Contain All the Attributes
}
public class Cone : Shape
{
    //Contain All the Attributes
}

This is nothing but the reusability feature that we achieved through inheritance. Next, what we are going to do is, we are going to create public constructors in each class and initialize the required attributes as follows.

public class Rectangle : Shape
{
    public Rectangle(double Height, double Width)
    {
        this.Height = Height;
        this.Width = Width;
    }
}
public class Circle : Shape
{
    public Circle(double Radius)
    {
        this.Radius = Radius;
    }
}
public class Triangle : Shape
{
    public Triangle(double Height, double Width)
    {
        this.Height = Height;
        this.Width = Width;
    }
}
public class Cone : Shape
{
    public Cone(double Radius, double Height)
    {
        this.Radius = Radius;
        this.Height = Height;
    }
}

Now, our requirement is to find out the Area of each shape i.e. area of Rectangle, area of Triangle, area of Circle, and area of Clone.

Where do we need to define that Area method?

We cannot define the area Method in the Shape class. Generally, what should come to Parent class means the things which are common for child classes. Now, we want a method that should return the area to an appropriate shape. Can we define that method in the Shape class? No. The reason is the formula to calculate the area varies from shape to shape. Because the formula varies from shape to shape, we cannot define that in the Parent class. This is the place where exactly abstract class and abstract method come into the picture.

The method cannot be defined in the Shape class, but it can be declared as an abstract method in the Shape class and once we declare the abstract method then we should also need to make the class abstract by using the abstract keyword as follows:

public abstract class Shape
{
    public double Height;
    public double Width;
    public double Radius;
    public const float PI = 3.14f;
    public abstract double GetArea();
}

Now, the GetArea abstract method must and should be implemented by all the child classes of the parent Shape class. Why? Because this is a rule. Once a Parent class contains any abstract methods, those abstract methods must be implemented by the child classes. And it is mandatory.

public class Rectangle : Shape
{
    public Rectangle(double Height, double Width)
    {
        this.Height = Height;
        this.Width = Width;
    }

    public override double GetArea()
    {
        return Width * Height;
    }
}
public class Circle : Shape
{
    public Circle(double Radius)
    {
        this.Radius = Radius;
    }

    public override double GetArea()
    {
        return PI * Radius * Radius;
    }
}
public class Triangle : Shape
{
    public Triangle(double Height, double Width)
    {
        this.Height = Height;
        this.Width = Width;
    }

    public override double GetArea()
    {
        return (Width * Height) / 2;
    }
}
public class Cone : Shape
{
    public Cone(double Radius, double Height)
    {
        this.Radius = Radius;
        this.Height = Height;
    }

    public override double GetArea()
    {
        return PI * Radius * (Radius + Math.Sqrt(Height * Height + Radius * Radius));
    }
}

So, this is the process of how we are going to use abstract classes and abstract methods in our application development using the C# language.

Now, you may have one question, why do we declare the GetArea method in the Parent class and implement it under the child classes, why we can’t directly define the GetArea method in the child classes? Yes. You can do this. But by declaring the GetArea method in the Shape class we have one advantage.

The advantage is that the method name is going to be the same in all four classes, and even if tomorrow a new class inherits the from the Shape class, then also the method name is going to be the same i.e. GetArea. Along with the method name, the method signature is also going to be the same in all the child classes.

For example, if four different people work on the project and if four different people work on a different, different shape, then there is no guarantee that all the developer is going to provide the same name and same signature for the method. The advantage of declaring the method in the Shape class is that, the name and signature are not going to vary in all four classes.

Example to Implement Abstract Classes and Abstract Methods in C# Application Development:

Whatever the example we have discussed, the complete example code is given below.

using System;
namespace AbstractClassesAndMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            Rectangle rectangle = new Rectangle(10, 20);
            Console.WriteLine($"Area of Rectangle: {rectangle.GetArea()}");

            Triangle triangle = new Triangle(15, 25);
            Console.WriteLine($"Area of Triangle: {triangle.GetArea()}");

            Circle circle = new Circle(12);
            Console.WriteLine($"Area of Circle: {circle.GetArea()}");

            Cone cone = new Cone(5, 15);
            Console.WriteLine($"Area of Cone: {rectangle.GetArea()}");

            Console.ReadKey();
        }
    }
   
    public abstract class Shape
    {
        public double Height;
        public double Width;
        public double Radius;
        public  const float PI = 3.14f;
        public abstract double GetArea();
    }

    public class Rectangle : Shape
    {
        public Rectangle(double Height, double Width)
        {
           this.Height = Height;
            this.Width = Width;
        }

        public override double GetArea()
        {
            return Width * Height;
        }
    }
    public class Circle : Shape
    {
        public Circle(double Radius)
        {
            this.Radius = Radius;
        }

        public override double GetArea()
        {
            return PI * Radius * Radius;
        }
    }
    public class Triangle : Shape
    {
        public Triangle(double Height, double Width)
        {
            this.Height = Height;
            this.Width = Width;
        }

        public override double GetArea()
        {
            return (Width * Height)/ 2;
        }
    }
    public class Cone : Shape
    {
        public Cone(double Radius, double Height)
        {
            this.Radius = Radius;
            this.Height = Height;
        }

        public override double GetArea()
        {
            return PI * Radius * (Radius + Math.Sqrt(Height * Height + Radius * Radius));
        }
    }
}
Output:

How to Use Abstract Classes and Abstract Methods in C# Application Development with Examples.

Abstract Class and Abstract Methods Example in C#:

In the below example, we calculate the electricity bills for commercial and domestic plans using abstract class and abstract methods.

using System;
namespace AbstractClassMethods
{
    public abstract class Plan
    {
        protected abstract  double getRate();
        public void Calculation(int units)
        {
            double rate = getRate();
            Console.WriteLine($"Bill Amount For {units} Units is: Rs. {rate * units}");
        }
    }

    class CommercialPlan : Plan
    {
        protected override double getRate()
        {
           return 5.00;
        }
    }
    class DomesticlPlan : Plan
    {
        protected override double getRate()
        {
            return 2.50;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Plan p;
            Console.WriteLine("Commercial Plan");
            p = new CommercialPlan();
            p.Calculation(250);

            Console.WriteLine("Domesticl Plan");
            p = new DomesticlPlan();
            p.Calculation(150);
            Console.ReadKey();
        }
    }
}
Output:

How to Use Abstract Classes and Abstract Methods in C# Application Development with Examples.

In the next article, I am going to discuss the Interface in C# with Examples. Here, in this article, I try to explain How to Use Abstract Classes and Abstract Methods in C# Application Development with Examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this How to Use Abstract Class and Abstract Methods in the C# Application Development Examples article.

2 thoughts on “How to Use Abstract Classes and Methods in C# Application”

  1. Hi, I have one question to the first example. Isnt problem that we inherit from Shape class all properties even those we dont use (like Rectangle has access to Radius, Circle has access to Height and Width etc.)?

    1. You can access to Radius field for Rectangle or Triangle objects but when you initialize their objects you only pass values to their Width and Height fields so as you can see there is no method that use could Radius in those classes, and it’s actually useless to pass a value to Radius because constructor already assign default value to it.

Leave a Reply

Your email address will not be published. Required fields are marked *