java - java中如何通过接口(interface)对象访问派生类成员变量?

标签 java inheritance extends implements

我是一名新的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/

相关文章:

java - (java.security.InvalidKeyException) 在 cipher.init(Cipher.DECRYPT_MODE, key) 出现预期错误时未设置 IV

c# - 如何检查一个接口(interface)是否在 C# 中扩展了另一个接口(interface)?

java - 将公共(public)父类(super class)的 Class 传递给 Function;函数应该检查对象是否是传递的类的实例

java - Android Java - 创建一个扩展现有类的接口(interface)

java - Hibernate 将 @Id 字段重构为父类(super class)

Javascript es6 覆盖静态属性

java - 如何在 spring boot 中连接到 MongoDB?

java - 将 double 转换为 32 位表示(和反向过程)

java - JavaFX 中的 FileChooser 给出 NullPointerException

c++ - 从派生类引用基类的更好习惯用法?