java - 如何指定要在具有多重继承的对象中使用哪个变量?
问题描述
所以我更深入地研究了一些多继承 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);
虽然您可以这样做,但通过实例访问static
成员是一种不好的做法(您会收到警告)。所以你应该简单地直接引用变量(值是静态的,所以它不能根据访问它的实例而有所不同):
System.out.println("x = " + Interface.x);
System.out.println("x = " + Base.x);
推荐阅读
- mysql - mysql 分组限制
- swift - 如何将 NSTextField 值转换为 CGFloat
- vba - VBA 字对齐语法
- c# - System.ComponentModel.Win32Exception (0x80004005):访问被拒绝
- javascript - console.log(document.meta) 元素未定义
- oauth-2.0 - Openid Connect:在依赖方之间共享 id 令牌
- javascript - 如何将输入 id 值存储到另一个页面上的变量中?
- c# - 创建模型时不能使用上下文。EF-Core ASP.net Core2.2
- java - 如何正确处理来自 Web 服务的 anyType()?
- java - 无法获得 Connect to Hive 版本 (2.1.0.2.6.3.0-235)