Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class inheriting from several Interfaces having same method signature

Tags:

c#

oop

interface

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. :(

like image 880
Manish Avatar asked May 14 '10 06:05

Manish


People also ask

Can a class implement two interfaces with the same method signature?

No, its an errorIf two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously.

What happens when a class implements multiple interfaces with same method declaration?

A class implementation of a method takes precedence over a default method. So, if the class already has the same method as an Interface, then the default method from the implemented Interface does not take effect. However, if two interfaces implement the same default method, then there is a conflict.

What happens when a class implements two interfaces both of which have the same method signature and return type?

If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error.

Can a class inherit from multiple interfaces?

Simply put, in Java, a class can inherit another class and multiple interfaces, while an interface can inherit other interfaces.


1 Answers

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
like image 117
Dean Harding Avatar answered Oct 10 '22 05:10

Dean Harding