Breaking News
Loading...
Friday 29 March 2013

How to use sealed keyword in .Net?


Sealed is a keyword used to restrict inheritance future of programing language. When you mark any class to be sealed then you cannot make it to be parent class of other child class. In java final keyword is used for this same purpose.

Example:

namespace CA_Sealed
{
    // declare sealed class
    public sealed class student()
    {
        public void std()
        {
            Console.WriteLine("This is sealed method");
        }
    }

    // here you cannot inherit properties of student class
    class Program
    {
        static void Main(string[] args)
        {
            student obj =new student();
            obj.std();
        }
    }
}


Output :

This is sealed method


You cannot declare method to be directly sealed but Methods of only derived class can be made sealed with keyword sealed.

Example :

namespace CA_Sealed
{
    // declare sealed class
    public  class student()
    {
        public virtual void std()
        {
            Console.WriteLine("This is base class method");
        }
    }
        
    // here you cannot inherit properties of student class
    class Program:student
    {
       public sealed override void std()
       {
           Console.WriteLine("This is derived class method");
       }
    }
}

See Also :
  Follow Me On Facebook


--
/\/ir@\/  <(.'.)>

0 comments:

Post a Comment

Thanks for comment

 
Toggle Footer