Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance from multiple interfaces with the same method name

If we have a class that inherits from multiple interfaces, and the interfaces have methods with the same name, how can we implement these methods in my class? How can we specify which method of which interface is implemented?

like image 739
masoud ramezani Avatar asked Mar 03 '10 12:03

masoud ramezani


People also ask

Can you inherit from two interfaces with the same method name in both of them?

C# allows the implementation of multiple interfaces with the same method name.

What happens if two interface have same method name?

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.

Can you inherit from multiple interfaces?

No you cannot inherit multiple interfaces, because interfaces cannot be inherited. Interfaces are IMPLEMENTED, not inherited.

What is multiple inheritance in Java using interface?

An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends multiple interfaces.


2 Answers

By implementing the interface explicitly, like this:

public interface ITest {     void Test(); } public interface ITest2 {     void Test(); } public class Dual : ITest, ITest2 {     void ITest.Test() {         Console.WriteLine("ITest.Test");     }     void ITest2.Test() {         Console.WriteLine("ITest2.Test");     } } 

When using explicit interface implementations, the functions are not public on the class. Therefore in order to access these functions, you have to first cast the object to the interface type, or assign it to a variable declared of the interface type.

var dual = new Dual(); // Call the ITest.Test() function by first assigning to an explicitly typed variable ITest test = dual; test.Test(); // Call the ITest2.Test() function by using a type cast. ((ITest2)dual).Test(); 
like image 56
Pete Avatar answered Sep 20 '22 16:09

Pete


You must use explicit interface implementation

like image 27
Gopher Avatar answered Sep 19 '22 16:09

Gopher