【问题标题】:How to access a derived class member variable by an interface object in java?java中如何通过接口对象访问派生类成员变量?
【发布时间】:2019-08-15 07:58:04
【问题描述】:

我是一个新的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[] 值成员吗?

【问题讨论】:

  • 你必须投到Object3Type
  • 父母了解孩子和兄弟姐妹之间相互了解并不是一个好习惯。
  • 不应该。如果您需要知道value 存在这一事实,那么您的代码需要使用正确的类型来表达该需求。在某些情况下,定义一个额外的接口HasValue 来表示这个概念可能是合适的。

标签: java inheritance extends implements


【解决方案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();
    }
}

【讨论】:

    猜你喜欢
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2020-04-29
    • 2015-02-04
    • 2021-12-05
    • 2016-01-05
    相关资源
    最近更新 更多