Back to: C#.NET Tutorials For Beginners and Professionals
Abstract Classes and Abstract Methods in C# with Examples
I will discuss Abstract Classes and Methods in C# with Examples in this article. Please read our previous article discussing Generalization and Specialization in C# with Examples. At the end of this article, you will understand the following pointers:
- What are Abstract Methods in C#?
- What are Abstract Classes in C#?
- What is the use of the Abstract Method in C#?
- Is Abstract Class Containing Only Abstract Methods in C#?
- Who will Provide the Implementation of Abstract Methods?
- Example to Understand Abstract Class and Abstract Methods in C#
- Can we create an instance of an Abstract Class in C#?
- Why Abstract Class Cannot Be Instantiated in C#?
- Can we Create a Reference for the Abstract Class in C#?
- When to use Abstract Classes and Methods in C#?
What are Abstract Methods in C#?
In C#, abstract methods are methods declared within an abstract class or an interface that do not have a method body or implementation in the declaring class or interface. Instead, the responsibility for implementing the method is delegated to any concrete (non-abstract) class that derives from the abstract class or implements the interface.
A method without the body is known as the Abstract Method. What the method contains is only the declaration of the method. That means the abstract method contains only the declaration, no implementation. The following method is a non-abstract method as this method contains a body.
public void Add(int num1, int num2)
{
}
But without writing the method body, if we end the method with a semicolon as follows, it is called an Abstract Method.
public void Add(int num1, int num2);
But remember, if you want to make any method an abstract method, then you should explicitly use the abstract modifier as follows. And once you use the abstract modifier, automatically, the method will be called an abstract method.
public abstract void Add(int num1, int num2);
Then, what are abstract classes?
What are Abstract Classes in C#?
In C#, an abstract class is a class that serves as a blueprint for other classes. Abstract classes cannot be instantiated directly, but they can be used as base classes for other classes that derive from them. Abstract classes are declared using the abstract keyword. They often define a common set of characteristics or behaviors that should be shared among multiple derived classes.
A class under which we define abstract methods is known as an abstract class. As per object-oriented programming, we need to define a method inside a class. We cannot define the abstract methods directly anywhere. We need to define the abstract method inside an abstract class only. Suppose we must write the above Add abstract method inside a Calculator class. Then, that class must be declared using the following abstract modifier.
public abstract class Calculator
{
public abstract void Add(int num1, int num2);
}
So, when a class contains any abstract methods, it must and should be declared using the abstract modifier, and when a class is created using an abstract modifier, it is called an Abstract class in C#. So, this is how exactly we define an abstract class and abstract methods in C#.
Generally, when we define an abstract class, we have a doubt: without a method body, what will be the use of that method? Let us understand this.
What is the use of the Abstract Method in C#?
If a method is declared abstract under any class, then the child class of that abstract class is responsible for implementing the abstract method without fail.
In inheritance, we see that the Parent class provides some properties to the Child class for consumption. Here also, the inheritance comes into the picture, but the point you need to remember is that the Parent class is abstract, and he will not provide any properties to the Child class for consumption. Rather, it imposes some restrictions on the Child classes. And children or Child classes have to be followed or fulfill those restrictions. And that is the basic idea of abstract class in C#. We will come to this point later.
Note: Every abstract method declared within an abstract class must and should be implemented by the Child classes without fail; otherwise, we will get a compile-time error.
Is Abstract Class Containing Only Abstract Methods in C#?
Don’t think an abstract class can contain only abstract methods. It can also contain non-abstract methods. You need to remember that if a class is non-abstract, it contains only non-abstract methods, but if a class is abstract, it contains both abstract and non-abstract methods in C#.
Who will Provide the Implementation of Abstract Methods in C#?
The Answer is Child Class. If you have a child class of an abstract class, then it is the responsibility of the child class to provide the implementation for all the abstract methods of the parent class. You cannot escape. Every method should be implemented. If you implement all the abstract methods, you can only consume the non-abstract method of the Parent class.
Generally, we saw in Inheritance that the child class can directly consume the members of the parent class. But here, this is not possible. You cannot consume directly. The property is under restrictions. Until and unless the child class fulfills the restrictions, the child class cannot consume the parent class members.
So, the point that you need to remember is that in the child class, you need to implement each and every abstract method of the parent class, and then only you can consume the non-abstract methods of the parent class.
Let us compare this with one real-time example. Suppose the father promised his son that if he brings 90% of the mark in the annual exam, he will be rewarded with a laptop. So, the laptop will only be given to the son if he brings 90% in the annual exam. Now, if the son wants to get the laptop, he has to fulfill the requirements set by his father. What is the requirement? The requirement is achieving 90% of the mark. Once the son fulfills the requirement, i.e., once he achieves 90% marks in the annual exam, the laptop is given to him. Until then, he will not get the laptop.
This is exactly the same in the case of an abstract class. Abstract class contains both abstract and non-abstract methods. You can consider the abstract method as Marks obtained on the annual exam and the non-abstract method as the laptop. So, if you want to get the laptop (i.e., to consume a non-abstract method), you need to fulfill the requirements, i.e., get 90% marks in the annual exam (i.e., implement all the abstract methods).
Note: To define a method as abstract or class as abstract, we need to use the abstract keyword.
Note: Abstract methods are commonly used within abstract classes. An abstract class cannot be instantiated; it serves as a blueprint for other classes. Abstract methods within an abstract class define a contract that any derived (sub) class must implement. An abstract class is declared using the abstract keyword.
Example to Understand Abstract Class and Abstract Methods in C#:
Let us understand Abstract Class and Abstract Methods in C# with an Example. Please have a look at the following class. This is going to be our parent abstract class. In this class, we have defined two non-abstract methods, i.e., Add and Sum, and two abstract methods, i.e., Mul and Div. Further, if you notice, we created the class AbsParent using the abstract keyword, as this class contains two abstract methods.
public abstract class AbsParent { public void Add(int x, int y) { Console.WriteLine($"Addition of {x} and {y} is : {x + y}"); } public void Sub(int x, int y) { Console.WriteLine($"Subtraction of {x} and {y} is : {x - y}"); } public abstract void Mul(int x, int y); public abstract void Div(int x, int y); }
Can we create an instance of an abstract class in C#?
No. We cannot create an instance of an abstract class. Whether the abstract class contains any abstract methods or not, creating an instance of the abstract class is impossible. If you try, you will get a compile-time error, as shown in the below image.
As you can see in the above image, it is clearly saying that you cannot create an instance of an abstract class, and this makes sense. This is because if it allows us to create an instance of the abstract class, then using the instance, you can call the abstract class abstract methods, which do not have a body, and this is the reason why it is not allowing us to create an instance of the abstract class in C#.
Currently, the abstract class does not have any static members. If there are any static members, you can call them directly using the class name. But, for calling non-static members, we need an instance. Then who can consume the above members? The answer is child class.
Suppose there is a child class for the above AbsParent class. Then, the child class has to implement the Mul and Div abstract methods before consuming the Add and Sub methods. Please observe the following code. Here, we have created the AbsChild class inheriting from the AbsParent class. Here, we have not implemented the two abstract methods. So, it is giving us a compile-time error.
Here, we are getting two errors. One for not implementing the parent class Div method and another error for not implementing the Parent class Mul method. That means it is mandatory for the child class to provide the implementation for all the abstract methods of the parent class.
Why Abstract Class Cannot Be Instantiated in C#?
Its abstract methods cannot be executed because it is not a fully implemented class. If the compiler allows us to create the object for an abstract class, we can invoke the abstract method using that object, which CLR cannot execute at runtime. Hence, to restrict calling abstract methods, the compiler does not allow us to instantiate an abstract class.
Now, let us implement the two abstract methods inside the child class. We must Implement the abstract methods using the override modifier as follows.
public class AbsChild : AbsParent { public override void Mul(int x, int y) { Console.WriteLine($"Multiplication of {x} and {y} is : {x * y}"); } public override void Div(int x, int y) { Console.WriteLine($"Division of {x} and {y} is : {x / y}"); } }
Now, you can see there is no more compile-time error. Now, the child class fulfills the requirements of the parent class by implementing the abstract methods; hence, the child class can now consume the non-abstract methods of the parent class. So, you can now create an instance of the Child class and consume all the members as follows.
The complete example code is given below.
using System; namespace AbstractClassesAndMethods { class Program { static void Main(string[] args) { AbsChild absChild = new AbsChild(); absChild.Add(10, 5); absChild.Sub(10, 5); absChild.Mul(10, 5); absChild.Div(10, 2); Console.ReadKey(); } } public abstract class AbsParent { public void Add(int x, int y) { Console.WriteLine($"Addition of {x} and {y} is : {x + y}"); } public void Sub(int x, int y) { Console.WriteLine($"Subtraction of {x} and {y} is : {x - y}"); } public abstract void Mul(int x, int y); public abstract void Div(int x, int y); } public class AbsChild : AbsParent { public override void Mul(int x, int y) { Console.WriteLine($"Multiplication of {x} and {y} is : {x * y}"); } public override void Div(int x, int y) { Console.WriteLine($"Division of {x} and {y} is : {x / y}"); } } }
Output:
Can we Create a Reference for the Abstract Class in C#?
Yes, we can create a reference for the abstract class in C#. But we cannot create an instance of an abstract class in C#. For a better understanding, please have a look at the below image. Here, we created an instance of the child class, i.e., AbsChild, and then we created a reference of the abstract class, i.e., AbsParent, which is holding the child class instance, and then using the reference, we can also access the members.
You need to remember that parent class references, even if created using child class instances, cannot be called child class methods, provided the methods are defined in the child class. Overridden methods are not pure child-class methods. If a method is overridden in the child class, it has taken permission from the parent class. So, the parent is completely aware of that method. So, the parent class references can also call the child class overridden members but cannot call the pure child class members.
To better understand this concept, please look at the example below. Here, the child class overrides the parent class members, and we defined a pure child class method, i.e., Mod in the child class. As this method is purely defined in the child class, we cannot call this method using the Parent class reference variable. Using the parent class reference variable, we can call the parent class non-abstract methods and child class overridden methods but not the pure child class methods.
using System; namespace AbstractClassesAndMethods { class Program { static void Main(string[] args) { //Creating Child class instance AbsChild absChild = new AbsChild(); //Creating abstract class reference pointing to child class object AbsParent absParent = absChild; //Accessing methods using reference absParent.Add(10, 5); absParent.Sub(10, 5); absParent.Mul(10, 5); absParent.Div(10, 2); //You cannot call the Mod method using Parent reference as it is a pure child class method //absParent.Mod(100, 35); Console.ReadKey(); } } public abstract class AbsParent { public void Add(int x, int y) { Console.WriteLine($"Addition of {x} and {y} is : {x + y}"); } public void Sub(int x, int y) { Console.WriteLine($"Subtraction of {x} and {y} is : {x - y}"); } public abstract void Mul(int x, int y); public abstract void Div(int x, int y); } public class AbsChild : AbsParent { public override void Mul(int x, int y) { Console.WriteLine($"Multiplication of {x} and {y} is : {x * y}"); } public override void Div(int x, int y) { Console.WriteLine($"Division of {x} and {y} is : {x / y}"); } public void Mod(int x, int y) { Console.WriteLine($"Modulos of {x} and {y} is : {x % y}"); } } }
Output:
When to use Abstract classes and Methods in C#?
You should consider using abstract classes and methods in C# when you want to:
- Define a Common Base: Abstract classes are useful when defining a common base for a group of related classes. If you have several classes with common properties, methods, or behavior, you can create an abstract base class to avoid duplicating code.
- Enforce a Contract: Abstract methods within abstract classes (or interfaces) allow you to enforce a contract that derived classes must adhere to. Abstract methods define a set of methods for which derived classes must provide concrete implementations, ensuring that certain functionality is available.
- Provide Default Implementations: Abstract classes can include both abstract and concrete members. You can provide default implementations in the abstract class that derived classes can choose to override or extend. This allows you to offer a common implementation while still allowing flexibility for customization.
- Implement Polymorphism: Abstract classes and methods are fundamental to achieving object-oriented programming polymorphism. You can create a collection of objects of different derived classes but treat them uniformly through the abstract base class or interface.
- Create Frameworks and Libraries: Abstract classes are often used to create frameworks, libraries, or APIs. By defining an abstract class with abstract methods, you specify a contract the client code must implement to use your framework effectively.
- Extend Functionality: Abstract classes allow you to extend functionality in a modular way. When adding new features or capabilities to a class hierarchy, you can create a new derived class from the abstract base class, implementing the necessary abstract methods.
- Ensure Code Consistency: Abstract methods enforce a consistent structure in derived classes. This can be especially useful in large development teams or projects requiring multiple developers to follow a common coding standard.
- Enable Code Reusability: By providing a common base class with shared functionality and structure, you promote code reusability. Code in the abstract base class can be used across multiple derived classes, reducing redundancy and maintenance efforts.
- Support Extension Points: Abstract methods in abstract classes act as extension points. They define areas where derived classes can add custom logic without modifying the core functionality of the base class.
- Implement Template Method Pattern: Abstract classes often play a role in implementing the Template Method design pattern. In this pattern, the abstract class defines the skeleton of an algorithm with certain steps marked as abstract methods, and derived classes provide specific implementations for those steps.
We should use abstract classes and methods to define a common base with shared functionality, enforce a contract, enable code reusability, and promote a consistent structure among related classes. They are essential tools in object-oriented programming for creating well-structured and extensible code.
Summary of Abstract Class and Abstract Methods in C#
- A method that does not have a body is called an abstract method, and the class that is declared using the keyword abstract is called an abstract class. If a class contains an abstract method, it must be declared abstract.
- An abstract class can contain both abstract and non-abstract methods. If a child class of an abstract class wants to consume any non-abstract methods of its parent, it should implement all abstract methods.
- An abstract class is never usable in itself because we cannot create the object of an abstract class. The members of an abstract class can be consumed only by the child class of the abstract class.
Abstract methods are useful when creating a base class or an interface with some common functionality that you want derived classes or implementing classes to inherit. Still, you require those classes to implement certain methods in their own way. This supports the principles of abstraction, polymorphism, and encapsulation in object-oriented programming, enabling code reusability and enforcing a consistent structure in your class hierarchy.
In the next article, I will discuss Abstract Classes and Abstract Methods Interview Questions and Answers in C# with Examples. In this article, I try to explain Abstract Classes and Abstract Methods in C# with Examples. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, questions, or comments about this Abstract Classes and Methods in C# with Example article.
Can you please explain below two points in details?When should a class be declared as abstract?
>>If it does not provide implementation to any of the abstract methods it inherited
>>If it does not provide implementation to any of the methods of an interface
>>If it does not provide implementation to any of the abstract methods it inherited
If your class inherits from an abstract class, you should override the abstract methods. In case you don’t override (aka, implement) the inherited abstract methods, your class becomes abstract by default – because it itself has abstract methods. Therefore, you must declare said class as abstract as well.
The same would then apply to interfaces.
Can you please explain ?
It is always created as a superclass next to the interface in the object inheritance hierarchy for implementing common operations from an interface. An abstract class may or may not have abstract methods. But if a class contains an abstract method then it must be declared as abstract.
Hi, in code here you have following:
//You cannot call the Mod method using Parent reference as it is a pure child class method
//absChild.Mod(100, 35);
First I must say that you can call that commented method. You probably wanted to say that you cant call this method:
//absParent.Mod(100, 35);
But still I would mention that you can use this to call that method:
((AbsChild)absParent).Mod(100, 35);
hi BARNABAS.666,
You are right. It is a type error. we have corrected the same. Yes, you can call the method like below. In this case, we are typecasting the object to AbsChild class and hence it will invoke the method from the AbsChild class.
((AbsChild)absParent).Mod(100, 35);
I have seen many tutorials gone through many articles and blogs but no one explained why interface why abstraction why inheritance clearly rather than explaining how to implement them but this site totally changed my way of understanding and i realized and started to sync it with real time world now its easy…i hope it would be grateful if these concepts are explained in videos.