I have interfaces A & B with a variable of same name but different value.
我有接口A和B与一个相同名称但不同的值的变量。
Interface A {
public static final int a = 50;
public void fun();
}
Interface B {
public static final int a = 60;
public void fun();
}
Another interface C extends A & B
另一个接口C扩展了A和B.
Interface C extends A, B {
public void fun();
}
A class D implements interface C
D类实现接口C.
Class D implements C {
public void fun() {
/* Some code */
}
}
What happens if i use D.a ? which one of the static variable a is inherited by the class D.
如果我使用D.a会怎么样?哪一个静态变量a是由类D继承的。
2 个解决方案
#1
2
Neither. When you do this, the reference to constant a
becomes ambiguous, requiring you to specify which one you want explicitly:
都不是。执行此操作时,对常量a的引用变得不明确,要求您明确指定要显示的内容:
public int fun() {
return a; // Get an error below
}
error: reference to "a" is ambiguous
错误:对“a”的引用含糊不清
public int fun() {
return B.a; // Works fine
}
#2
1
It's ambiguous to the compiler and will cause an error when used, something like the field is ambiguous. Since the field is static
, you can resolve against the class name, e.g. A.a
or B.a
.
它对编译器来说是模糊的,并且在使用时会导致错误,类似于字段是不明确的。由于该字段是静态的,因此您可以针对类名进行解析,例如A.a或B.a.
#1
2
Neither. When you do this, the reference to constant a
becomes ambiguous, requiring you to specify which one you want explicitly:
都不是。执行此操作时,对常量a的引用变得不明确,要求您明确指定要显示的内容:
public int fun() {
return a; // Get an error below
}
error: reference to "a" is ambiguous
错误:对“a”的引用含糊不清
public int fun() {
return B.a; // Works fine
}
#2
1
It's ambiguous to the compiler and will cause an error when used, something like the field is ambiguous. Since the field is static
, you can resolve against the class name, e.g. A.a
or B.a
.
它对编译器来说是模糊的,并且在使用时会导致错误,类似于字段是不明确的。由于该字段是静态的,因此您可以针对类名进行解析,例如A.a或B.a.