Loading...

Sealed Classes and Methods in OOP C#

Sealed Class in C#:

A sealed Class can not be inherited by any other class, an error will be occur if you use a sealed Class as a base class ans simple you can not use it as a base class. Use the "sealed" modifier when you declare a class to prevent inheritance of the class.
You can not use the abstract modifier with a sealed class.
Example:

sealed class Base
{
    //any valid code goes here
}

//Error: Cannot inherit a sealed class
class Derived : Base
{

}

Sealed Function in C#:
If you use sealed modifier with an instance method declaration, that method is called sealed Method, You also must have used override keyword with sealed modifier.

Sealed method can not be further overridden by another derived class. Example:

class A
{
    public virtual void F()
    {
        Console.WriteLine("A.F");
    }
    public virtual void G()
    {
        Console.WriteLine("A.G");
    }
}
class B : A
{
    sealed override public void F()
    {
        Console.WriteLine("B.F");
    }
    override public void G()
    {
        Console.WriteLine("B.G");
    }
}
class C : B
{  
    override public void F()//Cannot override sealed method
    {
        Console.WriteLine("C.F");
    }
    override public void G()
    {
        Console.WriteLine("C.G");
    }

}
Thanks to msdn.microsoft.com for knowledge and examples
Hit Like Button if you understood, It helps a lot to keep us Motivated.

0 comments:

Post a Comment

Google+

 
TOP