Interface Ambiguous Fields
What will be the output of compiling and running the following program:
interface I1{
int VALUE = 1;
void m1();
}
interface I2{
int VALUE = 2;
void m1();
}
class TestClass implements I1, I2{
public static void main(String[] args){
I1 i1 = new TestClass();
i1.m1();
}
public void m1() {
System.out.println("Hello");
System.out.println(I1.VALUE);
System.out.println(I2.VALUE);
}
}
The output for the above program is
Hello
1
2
Ad Java Reference
Ambiguous Interface Fields
Having ambiguous fields does not cause any problems but referring to such fields in an ambiguous way will cause a compile time error. So you cannot execute the following statement in your code:
System.out.println(VALUE);
//The field VALUE is ambiguous
because it is ambiguous.
You can refer to a static variable of an interface by associating the static variable with the interface:
For example, I3.VALUE and I4.VALUE as in the example below.
interface I3{
int VALUE = 5;
void m1();
}
interface I4{
int VALUE = 7;
void m1();
}
public class AlteredClass implements I3, I4{
public static void main(String[] args) {
AlteredClass ac1 = new AlteredClass();
ac1.m1();
System.out.println("I3.VALUE= " + I3.VALUE);
System.out.println("I4.VALUE= " + I4.VALUE);
}
public void m1() {
System.out.println("Within method m1()");
}
}
//Program output
Within method m1()
I3.VALUE= 5
I4.VALUE= 7