简体   繁体   中英

Ambiguity for Variable but not for Method

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?

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 Aa or Ba you just need to prefix it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM