如何指定要在具有多重继承的对象中使用的变量?

时间:2018-12-19 17:13:18

标签: java inheritance

所以我正在深入研究一些多重继承Java东西,因此是我的问题:

class Base {
    static int x = 10;
}

interface Interface {
    int x = 20;
}

class MultipleInheritance extends Base implements Interface {   
    int z = 2 * Interface.x; // here I have both variables from interface and base class
    // I can use either "Interface" or "Base" to specify which 'x' variable I want to use
}

class TestClass {

    void aMethod(MultipleInheritance arg) {
        System.out.println("x = " + arg.x); // compiler error
        // how to specify which 'x' variable I want to use here?
    }

}

2 个答案:

答案 0 :(得分:3)

您可以投射:

System.out.println("x = " + ((Interface)arg).x);
System.out.println("x = " + ((Base)arg).x);

尽管您可以执行此操作,但是通过实例访问static成员是一种不好的做法(您会得到警告)。因此,您应该简单地直接引用变量(该值是静态的,因此根据访问它的实例,它不能有所不同):

System.out.println("x = " + Interface.x);
System.out.println("x = " + Base.x);

答案 1 :(得分:2)

与方法引用不同,字段引用不是多态的。它们在编译期间由引用类型解决。

如果必须使用对象引用,则可以自己转换引用类型来决定使用哪种对象

System.out.println("x = " + ((Interface) arg).x); 
System.out.println("x = " + ((Base) arg).x);