Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何指定要在具有多重继承的对象中使用的变量?_Java_Inheritance - Fatal编程技术网

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

Java 如何指定要在具有多重继承的对象中使用的变量?,java,inheritance,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 interfac

因此,我深入研究了一些多重继承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?
    }

}
你可以投:

System.out.println("x = " + ((Interface)arg).x);
System.out.println("x = " + ((Base)arg).x);
虽然您可以这样做,但通过实例访问静态成员是一种不好的做法,因为您会收到警告。因此,您只需直接引用变量即可。该值是静态的,因此根据访问该值的实例,该值不能有所不同:

System.out.println("x = " + Interface.x);
System.out.println("x = " + Base.x);
你可以投:

System.out.println("x = " + ((Interface)arg).x);
System.out.println("x = " + ((Base)arg).x);
虽然您可以这样做,但通过实例访问静态成员是一种不好的做法,因为您会收到警告。因此,您只需直接引用变量即可。该值是静态的,因此根据访问该值的实例,该值不能有所不同:

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

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

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

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

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

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

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

变量是静态的,不是继承的。变量是静态的,不是继承的。