tags:

views:

145

answers:

2

Say, I have three interfaces:

public interface I1
{
    void XYZ();
}
public interface I2
{
    void XYZ();
}
public interface I3
{
    void XYZ();
}

A class inheriting from these three interfaces:

class ABC: I1,I2, I3
{
      // method definitions
}

Questions:

  • If I implement like this:

    class ABC: I1,I2, I3 {

        public void XYZ()
        {
            MessageBox.Show("WOW");
        }
    

    }

It compiles well and runs well too! Does it mean this single method implementation is sufficient for inheriting all the three Interfaces?

  • How can I implement the method of all the three interfaces and CALL THEM? Something Like this:

    ABC abc = new ABC();
    abc.XYZ(); // for I1 ?
    abc.XYZ(); // for I2 ?
    abc.XYZ(); // for I3 ?
    

I know it can done using explicit implementation but I'm not able to call them. :(

+2  A: 

You can call it. You just have to use a reference with the interface type:

I1 abc = new ABC();
abc.XYZ();

If you have:

ABC abc = new ABC();

you can do:

I1 abcI1 = abc;
abcI1.XYZ();

or:

((I1)abc).XYZ();
Matthew Flaschen
I want to call that on object of ABC... ABC abc = new ABC(); ...
Manish
+7  A: 

If you use explicit implementation, then you have to cast the object to the interface whose method you want to call:

class ABC: I1,I2, I3
{
    void I1.XYZ() { /* .... */ }
    void I2.XYZ() { /* .... */ }
    void I3.XYZ() { /* .... */ }
}

ABC abc = new ABC();
((I1) abc).XYZ(); // calls the I1 version
((I2) abc).XYZ(); // calls the I2 version
Dean Harding
Interesting that this is possible in C#! Implementing colliding interface methods separately in the same class is impossible in Java, as far as I know.
Christian Semrau
It's possible, yes, though I would generally not recommend it (it's confusing). The only place I think it's legitimate is when doing stuff like implementing `ICollection<T>` and you want to 'hide' the non-generic `IEnumerable` implementation from the normal class definition.
Dean Harding