英文:
Ambiguity for Variable but not for Method
问题
我们有一个没有关联的interface
和class
,它们都有具有相同签名的方法。这些可以关联到一个类,这样编译就不会出错。
但是,当我们在变量上做同样的操作时,会导致歧义。
即使我们在B
中将a
声明为final
,仍然会导致错误。为什么方法是有效的,而变量无效呢?
英文:
We have an interface
and class
with no relation each having methods with same signature. These can be related to a class which would compile fine.
interface A {
void test();
}
class B {
public void test() {
System.out.println("Test");
}
}
public class MultipleLevelInheritance extends B implements A {
public static void main(String[] args) {
new MultipleLevelInheritance().test();
}
}
But when we do the same with the a variable its causing ambiguity.
interface A {
int a = 10;
}
class B {
public static int a = 9;
}
public class MultipleLevelInheritance extends B implements A {
public static void main(String[] args) {
System.out.println(a); //The field a is ambiguous
}
}
Even if we keep a
as final in B
, its still causing the error. Why is that valid for methods and invalid for variables?
答案1
得分: 1
当您实现一个接口时,所有变量都会在类中继承。因此,当您扩展一个类并实现接口时,会有两个变量a的声明。因此您会收到模糊性错误。
但是当涉及到方法时,当您实现接口时,您需要提供接口中定义的方法的实现。在您的示例中,这个实现由类B提供。因此不会有错误。
英文:
When you implement an interface, all variables are inherited in the class. So, when you extend a class and implements the interface, it will have two declaration of variable a. Hence you are getting ambiguity error.
But when it comes to methods, when you implement the interface, you are expected to provide the implementation of the methods defined in interface. In your example, this implementation is provided by class B. Therefore there is no error.
答案2
得分: 0
你的类MultipleLevelInheritance同时实现了一个接口并继承了一个类,而且它们都有相同的属性名称(a)。当你在MultipleLevelInheritance中调用a时,Java无法确定该变量是指A.a还是B.a。你只需要在前面加上前缀即可。
英文:
Your class MultipleLevelInheritance is implementing an interface and extending a class, and both have the same property name (a),when you call a in MultipleLevelInheritance, Java is not able to determine if the variable refers to A.a or B.a. you just need to prefix it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论