In: Finance
Assume that there is a class named TestInterface that implements two interfaces A and B. Both the interfaces have a common method with the same signature (example int sampleMethod()). Explain how will the class define this method and how will the compiler identify, to which interface does this method belong to? Will the compiler give an error or will the program execute successfully. Give your code snippet to support your answer.
I have implemented the code,as you mentioned in the question
And i observed that the type of implementation of two interfaces by the same method is executable.
The compiler implementing the sample method for both interfaces. its taking the both method implementations at a time because both the methods have same name.
Because of the same method name the implementation of two interfaces A and B is done in one method only.
if you change any method name in any interface,then you have to provide implementation for both methods,
otherwise it will generate a compiler error.
in our case both method signatures are same,no need of providing implementation for both methods.
source code:
//defining interface A,
//with a sample method,
interface A{
int samplemethod();
}
//defining interface B
//with same sample method as in interface A
interface B{
int samplemethod();
}
//implementing interface A and B,using TestInterface class
class TestInterface implements A,B{
//implementing samplemethod
public int samplemethod(){
System.out.print(" Hello,How are you ? ");
return 0;
//in both interfaces we have same method, with same
method signature,so we can implement only one method
}
public static void main(String args[]){
//creating object for TestInterface
TestInterface obj=new TestInterface();
//calling sample method with TestInterface object
obj.
obj.samplemethod();
}
}
output
comment if you have any questions