With the introduction of default methods in interfaces in Java 8, multiple inheritance may occur, which are resolved by these rules in case of methods. But these rules are not the same in case of member variables. Consider the following example.
public class MyClass {
public static void main(String args[]) {
Hello h = new Hello();
h.sayHello();
}
}
interface A{
String temp = "A";
default public void print() {
System.out.println("A");
}
}
interface B extends A{
String temp = "B";
}
interface C extends A{
default public void print() {
System.out.println("C");
}
}
class Hello implements B, C {
public void sayHello() {
print();
System.out.println(temp);
}
}
In the above case, implementation of the print() method is taken from interface C, but for variable "temp", the following error occurs:
/MyClass.java:28: error: reference to temp is ambiguous System.out.println(temp); ^ both variable temp in B and variable temp in A match 1 error
Why is this so?