Sealed classes are used in C# to prevent any class from inheritance. We cannot inherit sealed classes in any other class. To make a class sealed class we place "sealed" keyword before the class declaration.
Syntax:
<sealed_keyword> <class_keyword> <class_name>
Sealed methods cannot be overridden. However, direct child class can only override the method, class that inherited the child class that cannot override the sealed methods. Basically in multilevel inheritance sealed keyword prevent the methods from multiple overridden. If you want to make a method as sealed then you have to put sealed keyword in child class before override and make it virtual in base class.
Syntax:
<sealed_keyword> override <accessmodifier> <return_type> <method_name>(){….};
Example of sealed class,
sealed class Bank {
public void AccountNo() {
Console.WriteLine("Account no for the given name is XXXXXXXX345");
}
}
class Customer: Bank //error
{
public void Display() {
Console.WriteLine("Name of the customer is XYZ");
}
}
class Program {
static void Main(string[] args) {
Customer obj = new Customer();
obj.Display();
}
}
Example of sealed method,
class Vehicle {
public virtual void TwoWheeler() {
Console.WriteLine("These type of vehicles are mostly of petrol");
}
public virtual void FourWheeler() {
Console.WriteLine("These type of vehicles are of both petrol and diesel");
}
}
class Car: Vehicle {
public sealed override void TwoWheeler() {
Console.WriteLine("Cars are not two wheelers");
}
public override void FourWheeler() {
Console.WriteLine("Cars comes under four wheeler type");
}
}
class Bike: Car {
//public override void TwoWheeler() //error
//{
// Console.WriteLine("Bikes comes under two wheeler type");
//}
public override void FourWheeler() {
Console.WriteLine("Bikes are not four wheelers");
}
}
class Program {
static void Main(string[] args) {
Bike obj = new Bike();
obj.FourWheeler();
Console.ReadLine();
}
}
Conclusion
Sealed classes and methods provide us with security feature of C#. We can make classes more secure and prevent them from inheritance.