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. :(
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.
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.
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.
Simply put, in Java, a class can inherit another class and multiple interfaces, while an interface can inherit other interfaces.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With