Sealed keyword is basically used to prevent from
inheritance. If class is declared as Sealed that means that class cannot be
inherited. Similarly, if a method is declared as Sealed that means that method cannot
be override in the further inherited class method. Sealed in method is always
used with override keyword.
Sealed method is used to define the overriding level of a
virtual method. By declaring method as sealed, we can avoid further redefining
and overriding of this method. In other word's we use "sealed" on a
method if we didn't want any derived classes to further override out method. A
sealed, overridden method prevents additional overriding.
The sealed modifier in the method always used with override.
Because the intention behind sealing a method is to stop further overriding of
it.
In other words, at any level of inheritance, if you want to
restrict the next level of derived classes from overriding a virtual method,
then create that method by using the keyword sealed along with the keyword
override.
Abstract modifier cannot be use with sealed class, because
an abstract class must be inherited by a class that provides an implementation
of the abstract methods or properties. When applied to a method or property,
the sealed modifier must always be used with override.
If we try to override sealed method then it will throw
compile time error that “cannot override
inherited member because it is sealed”
E.G.
class ChildClass : ParentClass
{
public void Test()
{
PublicMethod();
ProtectedMethod();
SealedMethod();
}
public sealed override void SealedMethod()
{
base.SealedMethod();
}
}
class Program: ChildClass
{
static void Main(string[] args)
{
ChildClass childObject = new ChildClass();
childObject.SealedMethod();
}
//public override void SealedMethod() //cannot override inherited member because it is sealed
//{
//}
}
class ChildClass : ParentClass
{
public void Test()
{
PublicMethod();
ProtectedMethod();
SealedMethod();
}
public sealed override void SealedMethod()
{
base.SealedMethod();
}
}
class Program: ChildClass
{
static void Main(string[] args)
{
ChildClass childObject = new ChildClass();
childObject.SealedMethod();
}
//public override void SealedMethod() //cannot override inherited member because it is sealed
//{
//}
}
Sealed Method Vs Private Method
No comments:
Post a Comment
This is a User Friendly Blog.
Simple Interface and Simple Controls are used.
Post your comments so i can modify blog regarding your wish.