Banner Ad

Sunday, March 16, 2014

Daily Interview Question #7: Implicit and Explicit Implementation of Interface

By Francis   Posted at   12:22 AM   OOPS interview Questions No comments

                                                   This is the most common interview question for experienced professionals.

Normally an interface can be implemented in a class in a normal way which is a implicit implementation. Sometime, we may have same method name in different interfaces. If this is the case, we need to do explicit implementation of the interface method. The main use of explicit implementation is to avoid the ambiguities between the class or method name. In order,  to do that the interface name put before that interface’s method.

 

Below example, shows the implicit and explicit implementation:

 

namespace ConsoleApplicationC
{
    // 2 interfaces with same method name
    interface IintegerAdd
    {
        void Add();
    }
    interface IfloatAdd
    {
        void Add();
        void Multiply();
    }


    // We implement Both interfaces
    class ArithmeticOperation : IintegerAdd, IfloatAdd
    {
        // Implicit  Implementation : There is no name collision so we can implement implicitly
        // NOTE : public modifier MUST here
        public void Multiply()
        {
            float a = 1.5f, b = 2.5f;
            Console.WriteLine("Float Multiplication is:" + a * b);
        }


        // Explicit Implementation :  Explicitly tell the compiler that we implement the interface IintegerAdd
        void IintegerAdd.Add()
        {
            int a = 10, b = 20;
            Console.WriteLine("Integer Addition Is:" + (a + b));
        }


        // Explicit Implementation :  Explicitly tell the compiler that we implement the interface IfloatAdd
        void IfloatAdd.Add()
        {
            float a = 1.5f, b = 2.5f;
            Console.WriteLine("Float Addition Is:" + (a + b));
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ArithmeticOperation objA = new ArithmeticOperation();
            IintegerAdd iobj = (IintegerAdd)objA;
            iobj.Add();
            IfloatAdd fobj = (IfloatAdd)objA;
            fobj.Add();
            Console.ReadKey();
        }
    }
}


Output :


 


Integer Addition Is:30
Float Addition Is:4

About Francis

Francis, an Associate at Cognizant. Having 7+ Years of experience in Microsoft web technologies.

0 comments :

Please give your valuable comments to improve the contents

Connect with Us