Wednesday, 15 February 2012

Can we implement few members of interface in derived class?


Yes, but that derived class should be abstract class.  It is possible whatever method doesn’t require implementation make them as abstract in derived class(should be abstract class).
    interface ISample
    {
        string Message();
        string SMS();
    }
ISample contains 2 method declarations.we have to implement them in derived class.
But I want provide implementation of single method only that is SMS().
    abstract class FirstClass:ISample
    {     
        public abstract string Message(); // not implemented here!       
        public string SMS()              // implemented
        {
            return "this implemented";
        }
    }
Yes we have to make them the members whatever methods we don’t provide implementation(definitation) as abstract----> Message() method in FirstClass(abstract class).

This method is available to derived classes of FirstClass as a virtual.(means we have to write override keyword in derived classes..like SecondClass.

Now I want to provide implementation(definitation) to my second method
-- >Message() also so now in my derived class(secondclass).
class SecondClass : FirstClass
    {
        public override string Message()  // Override keyword is must.
        {
            return "this also implemented ";
        }
        public string Normalmethod()
        {
            return "dafsdfasd";

        }
        static void Main()
        {
            SecondClass sobj = new SecondClass();
            string smsg = sobj.Message();
            Console.WriteLine(smsg);
            string ssms = sobj.SMS();
            Console.WriteLine(ssms);
            string n = sobj.Normalmethod();
            Console.WriteLine(n);
            Console.Read();  
       
        }
}
Conclusion: Interface members are may or may not be implemented in abstract class.but Finally all the members should be implemented in below derived classes of abstract class.

No comments:

Post a Comment