Sunday, 4 March 2012

What is Sealed Method in a class?

Yes,till now we know about sealed class.
like
selaed class is final derived class.which can't be inherited.
to make use of sealed key word we can prepare a sealed class.
we can create instance to these classes.
Sealed class are opposite to abstract classes.
Ex:  SqlConnection.---System.Data.SqlClient;


Ex:

 class ParentClass
    {
        public virtual int  ArtimaticOperation(int x, int y)
        {
            return x + y;
        }
    }
Here ArtimaticOperation is one Virtual method means we can override in derived classes.

class ChildClass:ParentClass
    {
        public override int ArtimaticOperation(int x, int y)
        {
            return x * y;
        }
        static void Main()
        {
            ParentClass pobj = new ParentClass();
            int addition = pobj.ArtimaticOperation(4, 5);
            Console.WriteLine(addition);
            ChildClass cobj = new ChildClass();
            int multi = cobj.ArtimaticOperation(4, 5);
            Console.WriteLine(multi);
            Console.ReadKey();     
        }     
    }
output:
       9---------addition result.
    20-------multiplication result.
Here the same ArtimaticOperation is giving 2 differnet funcationalities why because virutal method is overrideed in derived class.
now again the funcationality also overrided in derived class. to restrict this use sealed keyword along with override keyword further classes can't override them.
class Sealedmethod ChildClass
    {
        public override Sealed  int ArtimaticOperation(int x, int y)
        {
            return x - y;
        }
        static void Main()
        {
            Sealedmethod sobj = new Sealedmethod();
            int sresult = sobj.ArtimaticOperation(10, 4);
            Console.WriteLine(sresult);
            Console.ReadKey();
        }
    }
but i want to restrict this funcationality in further derived classes. so make use of keyword is Sealed.
write along with override sealed further derived classes can't be override the existing funcatinality.

Ex : GridView control----->contains ---public override sealed void DataBind();

No comments:

Post a Comment