Abstract Class and Method in C#

Abstraction in C# is a process to hide the internal details, without generating affection on showing its functionality.  Compared with Encapsulation, Abstraction is an umbrella term, whereas Encapsulation is to protect a class’ properties from any corruption access. We can go a long way without needing an abstract class, but abstract class is a good approach for frameworks, complex class configuration, etc. It can save a lot repeated work.

In C#, abstraction can be achieved by using abstract class and interfaces.  In this post, we mainly focus on abstract class.

Abstract class in C# is marked by keyword abstract.  It serves as a base class, which is designed to be inherited by subclasses.  

Key Points

  • Abstract Class is achieved by add keyword abstract in class declaration
  • Objects or instances cannot initialized from abstract class  
  • Objects or instances can only initialized from abstract class’ subclass
  • There must be at least one abstract class method in each abstract class; we don’t need to supply the implementation detail for it. However, when we implement it in subclass, we need to override it
  • Abstract class can contain non-abstract methods; we need to supply the implementation detail for it
  • User must override abstract class method when we implement abstract class method in its subclass

Talk Is Cheap, Show Me The Code

Case Study

Image we have a university student’s record in the office and we need to get his/her GPA and access how good the GPA is. We declare a class Person, which is an abstract class in this project and it serves as a base class. In the Person class, there is one abstract class method and one non-abstract class method.

We also declare a subclass named Student, which is inherited from Person class.

As you can see, ComputeGradeAverage() is an abstract class method and Student class need to override it when it is implemented in Student class. OverallAcademicPerformance() is a non-abstract class method, we need to provide the implementation when we declare it in the Person class.

Email Subscription

Leave a Reply

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