为什么这会导致"The field name is ambiguous"错误?



以下是代码:

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";
}

以下是它导致的错误:

字段名称不明确

问题出在哪里?什么是模棱两可的?

您的类实现了两个接口,在这两个接口上都定义了变量name。因此,当您在类中调用name时,Java无法确定该变量是指Interface1.name还是指Interface.name

这就是代码中的问题。。。

MyClass实现了两个接口,这两个接口都有一个name变量。在MyClass的构造函数中,Java不知道从Inreface1中选择哪个name,或者从Inreface2中选择哪个。你可以明确地告诉它:

public MyClass() {
    System.out.println("name is :: " + Inreface1.name);
}

查看您的代码:

System.out.println("name is :: " + name);

编译器应该使用哪个"名称"?我不清楚,因为可能是Inreface1.name或Inreface2.name。如果您通过指定一个"名称"来消除歧义,则错误应该会消失。例如:

System.out.println("name is :: " + Inreface1.name);

什么是模棱两可的

如果一个接口继承了具有相同名称的两个字段例如,因为它的两个直接超接口声明字段使用该名称,则会产生一个不明确的成员。任何使用此不明确的成员将导致编译时错误。因此,在示例:

   interface BaseColors {
        int RED = 1, GREEN = 2, BLUE = 4;
    }
    interface RainbowColors extends BaseColors {
        int YELLOW = 3, ORANGE = 5, INDIGO = 6, VIOLET = 7;
    }
    interface PrintColors extends BaseColors {
        int YELLOW = 8, CYAN = 16, MAGENTA = 32;
    }
    interface LotsOfColors extends RainbowColors, PrintColors {
        int FUCHSIA = 17, VERMILION = 43, CHARTREUSE = RED+90;
    }

接口LotsOfColors继承了两个名为YELLOW的字段。这是只要接口不包含任何引用字段黄色的简单名称。(此类引用可能发生在字段的变量初始值设定项。)

即使接口PrintColors将值3赋予黄色而不是值8,a对接口LotsOfColors中字段YELLOW的引用仍然是被认为是模棱两可的。

另一点是接口中不允许使用实例变量。您的公共字符串变为常量:public static string name;-你得到两次。多个具有相同名称/类型的常量肯定是不明确的。

看起来您引用的是同一个变量。

我想编译器不知道你要传递哪个值。你试过更改字段变量吗?

相关内容

最新更新