What is sealed class and sealed method?
In this article, I will try to explain sealed class and sealed method in a very simple way.
Sealed Class
Sealed class is used to define the inheritance level of a class.
The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class.
Some points to remember:
- A class, which restricts inheritance for security reason is declared sealed class.
- Sealed class is the last class in the hierarchy.
- Sealed class can be a derived class but can't be a base class.
- A sealed class cannot also be an abstract class. Because abstract class has to provide functionality and here we are restricting it to inherit.
Practical demonstration of sealed class
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace sealed_class
- {
- class Program
- {
- public sealed class BaseClass
- {
- public void Display()
- {
- Console.WriteLine("This is a sealed class which can;t be further inherited");
- }
- }
- public class Derived : BaseClass
- {
-
- }
- static void Main(string[] args)
- {
- BaseClass obj = new BaseClass();
- obj.Display();
- Console.ReadLine();
- }
- }
- }
Sealed Methods
Sealed method is used to define the overriding level of a virtual method.
Sealed keyword is always used with override keyword.
Practical demonstration of sealed method
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace sealed_method
- {
- class Program
- {
- public class BaseClass
- {
- public virtual void Display()
- {
- Console.WriteLine("Virtual method");
- }
- }
- public class DerivedClass : BaseClass
- {
-
- public override sealed void Display()
- {
- Console.WriteLine("Sealed method");
- }
- }
-
-
-
-
-
-
-
- static void Main(string[] args)
- {
- DerivedClass ob1 = new DerivedClass();
- ob1.Display();
- Console.ReadLine();
- }
- }
- }
Hope this article will give you better view of sealed class and sealed method. Waiting! for your valuable feedback.