In this article, we will check out the difference between the Sealed and Abstract classes in c#. Also, we will review how we can utilize both types of classes while developing the application with real-time examples.
Sealed Class
A Class restricted to inheriting/deriving a new class is called a sealed class. In other words, we can say a class defined with a sealed keyword/modifier is known as a sealed class and it will not allow deriving a new class.
Code sample for sealed class
public sealed class BaseClass
{
public void ShowUser()
{
Console.WriteLine("Show user details");
}
}
Error. 'class2': cannot derive from sealed type ‘BaseClass’.
Sealed Methods
The methods defined in the parent class with sealed keywords that cannot be overridden under the child class are known as sealed methods.
Let’s consider the below example of sealed methods.
Explanation
In the above example, we have the base class “Calculator” and the derived class “Sum”. The calculate() method is defined with a sealed keyword under the Sum class. Now if we try to create the derived class of Sum class called “Sum_Detail”, it won’t allow us to override the calculate method and throws the compile time error “cannot override inherited member 'Sum.calculate()' because it is sealed”.
Examples
A real-time scenario where we can use the sealed class. In the e-commerce application, we need to implement a payment gateway. We need a restriction that no one can override the core logic of the payment or refund. As per the below screen print of the sample code structure, we can use the sealed class to prevent overriding the core logic of payment.
The sqlConnection class is another realtime example of a sealed class.
Abstraction
Abstraction is the process of hiding the details and showing only certain details to the user. It can be used with either abstract classes or interfaces.
- Abstract Class: A class defined with an abstract keyword will not allow the creation of objects of the class. Only need to inherit to use these classes.
- Abstract Method: A method that does not have a body in the base class or Abstract class and a body provided in the derived class is known as an abstract method. Abstract methods can be used only in abstract classes.
Abstraction Example
Let’s consider the below example of Abstract class and methods.
Can Abstract class be sealed class?
Difference between the Sealed class and the Abstract Class
No. Abstract Classes Can’t Be Sealed. Below are the reasons.
- Design Conflict in Inheritance: Sealing the class indicates the prevention of inheritance while abstraction is designed to inherit, the principle of polymorphism and shared behavior, creating a fundamental conflict.
- Enabling Further Abstraction: Sealing an abstract class would obstruct the natural of abstraction, limiting the affability of the code. Abstract classes are frequently used to define common functionality while leaving certain details to be implemented by derived classes.