首页 > 解决方案 > 如何指定要在具有多重继承的对象中使用哪个变量?

问题描述

所以我更深入地研究了一些多继承 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?
    }

}

标签: javainheritance

解决方案


你可以投:

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);

推荐阅读