Explicit interface implementation

We have to do explicit interface implementation when implementing interfaces with collision.

In the following code we have two interfaces. Then have the methods with identical signature.

We do the explicit interface implementation by adding interface name in front of the method name.


using System;
interface Printable{
   void print();
}

interface Outputable{
   void print();
}
class MyClass: Printable, Outputable{
  public void print(){
     Console.WriteLine("Printable.print");
  }
  void Outputable.print(){
     Console.WriteLine("Outputable.print");
  }
}

class Test
{
    static void Main()
    {
        MyClass cls = new MyClass();

        cls.print();
        ((Outputable)cls).print();

    }
}

From the code above we can see that when calling the explicited interface implementation we have to the cast.

The output:


Printable.print
Outputable.print
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.