为什么这会导致“字段名称不明确”?错误?
这是代码:
public class MyClass implements Inreface1, Inreface2 {
public MyClass() {
System.out.println("name is :: " + name);
}
public static void main(String[] args) {
new MyClass();
}
}
//Interface1
public interface Inreface1 {
public String name="Name";
}
//Interface2
public interface Inreface2 {
public String name="Name";
}
这是它导致的错误:
字段名称不明确
是什么问题?什么是暧昧?
Here is the code:
public class MyClass implements Inreface1, Inreface2 {
public MyClass() {
System.out.println("name is :: " + name);
}
public static void main(String[] args) {
new MyClass();
}
}
//Interface1
public interface Inreface1 {
public String name="Name";
}
//Interface2
public interface Inreface2 {
public String name="Name";
}
Here is the error it causes:
The field name is ambiguous
What is the problem? What is ambiguous?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您的类正在实现两个接口,并且在这两个接口上都定义了变量
name
。因此,当您在类中调用name
时,Java 无法确定该变量是引用Interface1.name
还是Interface.name
。这就是你的代码的问题...
Your class is implementing two interfaces, and on both of them, the variable
name
is defined. Thus, when you callname
in your class, Java is not able to determine if the variable refers toInterface1.name
orInterface.name
.That's the problem in your code...
MyClass
类实现了两个接口,它们都有一个name
变量。在MyClass
的构造函数中,Java 不知道选择哪个name
- 是Inreface1
中的名称还是Inreface2< 中的名称/代码>。你可以明确地告诉它:
Class
MyClass
implements two interfaces, which both have aname
variable. In the constructor ofMyClass
, Java doesn't know whichname
to pick - the one fromInreface1
or the one fromInreface2
. You could tell it explicitly:看看你的代码:
编译器应该使用哪个“名称”?我很模糊,因为可能是 Inreface1.name 或 Inreface2.name。
如果您通过指定一个“名称”来消除歧义,则错误应该会消失。例如:
Look at your code:
Which "name" should the compiler use? I's ambiguous, because could be Inreface1.name or Inreface2.name.
If you clear the ambiguity by specifying one "name" the error should disappear. For instance:
还有一点是接口中不允许有实例变量。你的公共字符串变成一个常量:public static String name; - 你会得到两次。多个具有相同名称/类型的常量肯定是不明确的。
Another point is that instance variables are not allowed in interfaces. Your public string turns into a constant : public static String name; - which you get two times. More than one constant with the same name/type is definitely ambiguous.
看来您引用的是同一个变量。
我认为编译器不知道您要传递哪个值。您是否尝试过更改字段变量?
It looks like you're referring to the same variable.
I think the compiler does not know which value you are trying to pass. Have you tried changing the field variable?