Java 如何指定要在具有多重继承的对象中使用的变量?
因此,我深入研究了一些多重继承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
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);
变量是静态的,不是继承的。变量是静态的,不是继承的。