变量存在歧义,但方法没有。

huangapple go评论65阅读模式
英文:

Ambiguity for Variable but not for Method

问题

我们有一个没有关联的interfaceclass,它们都有具有相同签名的方法。这些可以关联到一个类,这样编译就不会出错。

但是,当我们在变量上做同样的操作时,会导致歧义。

即使我们在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.

huangapple
  • 本文由 发表于 2020年8月9日 23:35:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63328218.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定