We have two interfaces and both have same method declaration, if any class implements these two interfaces which interface method will be executed?
package com.util;
public class Test3 implements Inter1, Inter2 {
public void fun(){
System.out.println("manikesh");
}
public static void main(String[] args) {
Test3 t3 = new Test3();
//System.out.println(t3.i);
t3.fun();
}
}
interface Inter1{
void fun();
//int i=6;
}
interface Inter2{
void fun();
//int i=8;
}
Can you guess the answer? Yes you got it right it will print manikesh.
Interfaces do not execute or define any method they just declare it so the implementer class really does not care which interface method it is.
All what compiler looks for is whether the method declared in interface has been defined in class or not.Both the interfaces can have any number of same type of method and implementer class has to define only one method.
But if we have same type of instance variable, can you guess the answer if I uncomment the commented code.
Can you guess the answer now? No you guessed it wrong it will throw error saying variable “I” is ambiguous because I has one values associated with that and both the interfaces cannot use the same.
Let’s see how we can write a code to accommodate such situation. I am just modifying the main method rest code would remain same.
public static void main(String[] args) {
//Test3 t3 = new Test3();
Inter1 I1 = new Test3();
Inter2 I2 = new Test3();
I1.fun();
I2.fun();
System.out.println(I1.i);
System.out.println(I2.i);
//t3.fun();
}
This will solve our problem, same we can do for any number of methods.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment