Aptitude (12) ASP.NET (2) Automata (4) Browser (1) C (5) C# (1) C++ (10) Code (3) CSS (1) Data Structure (1) DATABASE (3) HTML (1) java (43) JSP (1) math (1) MySql (8) other (6) php (3) Servlet (3)

Saturday, 11 May 2013

c#: shield class

c#: shield class


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#: 
// 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.


using System;
class Class1
{
    static void Main(string[] args)
    {
        SealedClass sealedCls = new SealedClass();
        int total = sealedCls.Add(45);
        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