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

问题描述 投票:0回答:1

我是一名新的java程序员。

我有以下类的层次结构:

public interface base

public interface Object1Type extends base

public interface Object2Type extends Object1Type

public class Object3Type implements Object2Type
{ 
      byte[] value;
} 

我有另一个类,我有一个Object1Type a的对象;

我可以使用这个对象访问Object3Type类型的byte []值成员吗?

java inheritance extends implements
1个回答
1
投票

你可以使用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算子检查一个对象。

我建议你在其中一个接口(现有的或新的)中声明一些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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.