我是一名新的java程序员。
我有以下类层次结构:
public interface base
public interface Object1Type extends base
public interface Object2Type extends Object1Type
public class Object3Type implements Object2Type
{
byte[] value;
}
我有另一个类,其中有一个 Object1Type a 的对象;
我可以使用此对象 a 访问 Object3Type 类型的 byte[] 值成员吗?
最佳答案
您可以使用class cast :
public static void main(String args[]) {
Object1Type a = new Object3Type();
if (a instanceof Object3Type) {
Object3Type b = (Object3Type) a;
byte[] bytes = b.value;
}
}
但这很危险,不推荐这样做。强制转换正确性的责任在于程序员。请参阅示例:
class Object3Type implements Object2Type {
byte[] value;
}
class Object4Type implements Object2Type {
byte[] value;
}
class DemoApplication {
public static void main(String args[]) {
Object1Type a = new Object3Type();
Object3Type b = (Object3Type) a; // Compiles and works without exceptions
Object4Type c = (Object4Type) a; // java.lang.ClassCastException: Object3Type cannot be cast to Object4Type
}
}
如果你这样做,至少用 instanceof 检查一个对象之前的运算符。
我建议您在其中一个接口(interface)(现有的或新的)中声明一些 getter 并在类中实现此方法:
interface Object1Type extends Base {
byte[] getValue();
}
interface Object2Type extends Object1Type {}
class Object3Type implements Object2Type {
byte[] value;
public byte[] getValue() {
return value;
}
}
class DemoApplication {
public static void main(String args[]) {
Object1Type a = new Object3Type();
byte[] bytes = a.getValue();
}
}
关于java - java中如何通过接口(interface)对象访问派生类成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55331662/