Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET,NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class, compiler throws an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
The following class definition defines a sealed class in C#:
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET,NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class, compiler throws an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
The following class definition defines a sealed class in C#:
// Sealed class
sealed class SealedClass
{
}
In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine. But if you try to derive a class from sealed class, you will get an error.
In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine. But if you try to derive a class from sealed class, you will get an error.
using System;
class Class1
{
static void Main(string[] args)
{
SealedClass sealedCls = new SealedClass();
int total = sealedCls.Add(4, 5);
Console.WriteLine("Total = " + total.ToString());
}
}
// Sealed class
sealed class SealedClass
{
public int Add(int x, int y)
{
return x + y;
}
}
No comments:
Post a Comment