Social Icons

Friday, 5 July 2013

Sealed Class in C#.Net with Example, what is the use of Sealed Class( Object Oriented Programming)

Sealed class in C#.Net


            Now we will see Sealed Class in C#.Net,why we use Sealed classes, How to consume Sealed class members etc.


 A class which is declared using sealed modifier is called as sealed class.A sealed class can not be inherited from any other class but we can consume that class by creating object of the class.

Example: String class in a sealed class which can not be inherited.

Mainly we use sealed classes to restrict a class having being derived by another class i.e Sealed Class can be Base Class, can not be inherited. The only way to consume sealed class members by creating instance variable using new keyword.(Object Creation). Sealed classes are faster at run time because of can not be a base class.

Sealed Method:

 A method which can not be overriden in child classes is called as sealed method. By default every method is sealed method where to consume any method of parent class in child class it needs to be declared as virtual otherwise we can not consume them.Use of sealed modifier prevents derived class for further overriding the method.

    If a method is declared as virtual under a class any child class in the linear hierarchy can override without any restriction.

        In the above case even if class2 can not override the Test() method still class3 can override the Test()
method because it is in linear hierarchy.

In the above case Test() method is overriden in class2 with sealed modifier so it can not be further overriden in its linear child  classes.

Sealed Class vs Static Class:

This is one of the important question in interviews i.e what is the difference between Sealed Class and Static Class. Sealed class is similar to static class i.e both can not be inherited. The only difference is you can use an instance variable to access sealed class members where as in static classes you will use class name.
Sealed Class:
--> Can create instances, but cannot inherit.
--> Can contain static as well as non-static members.
--> Contains a public Constructor.
 Static Classes:
--> Can neither create their instances, nor inherit them.
--> Can have static members only.
--> Contains a private Constructor.


I hope my small work on Sealed Classes in C#.Net will Help to You.I would like to take feedback from you.

Related Articles:



Please Give your Valuable Suggestions,Questions and Comments to improve my blog.