In this article, we will learn about the sealed class and method in C#.
C# Sealed Class
A sealed class, in C#, is a class that cannot be inherited by any class but can be initiated.
When we don't want a class can be inherited by another class, We can declare that class as sealed class.
A sealed class cannot have a derived class. We use the sealed keyword to create a sealed class.
sealed class Vehicle {
}
class Car : Vehicle {
}
class Program {
public static void Main(string[] args)
{
Car car = new Car();
Console.ReadLine();
}
}
In the above example, we have created a sealed class Vehicle and then we are trying to derived Car class from the Vehicle class. when we are trying to compile code it'll give following errors.
C# Sealed Method
When we don't want method can be override by another class, We can declare that method as sealed method.
We use a sealed keyword with an overridden method to create a sealed method.
class Vehicle {
public virtual void Color() {
Console.WriteLine("Vehicle color red");
}
}
class Car : Vehicle
{
sealed public override void Color() {
Console.WriteLine("Car color red");
}
}
class Audi : Car
{
public override void Color()
{
Console.WriteLine("Audi color red");
}
}
class Program {
public static void Main(string[] args)
{
Audi car = new();
car.Color();
Console.ReadLine();
}
}
In the above example, we have overridden the Color method of Car class inside the Audi class.
Notice that we have used sealed keyword with method Color(). This means that Audi class that inherits Car class is not allowed to override Color() method. So we get the following error.
Comments
Post a Comment