在java中,如何通过接口对象访问派生类成员变量?

在java中,如何通过接口对象访问派生类成员变量?,java,inheritance,extends,implements,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; } 我有另一个类,其中我有一个object1typea的对象 我可以使

我是一名新的java程序员

我有以下层次结构的类:

public interface base

public interface Object1Type extends base

public interface Object2Type extends Object1Type

public class Object3Type implements Object2Type
{ 
      byte[] value;
} 
我有另一个类,其中我有一个object1typea的对象

我可以使用此对象访问Object3Type类型的byte[]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
    }
}
如果这样做,至少要事先与操作符检查一个对象

我建议您在其中一个接口(现有或新)中声明一些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();
    }
}

您必须转换为
Object3Type
父母了解孩子和兄弟姐妹彼此了解不是一个好做法。您不应该这样做。如果您需要知道
value
存在的事实,那么您的代码需要使用正确的类型来表达这种需要。在某些情况下,可以定义一个额外的接口
HasValue
来表示这个概念。
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();
    }
}