Java方法据说返回类的对象但返回子类的对象

标签 java casting return-type

a method :

public DimseRSP cfind(String asuid, String cuid, int priority,
        Attributes data, String tsuid, int autoCancel) throws IOException,
        InterruptedException {
    FutureDimseRSP rsp = new FutureDimseRSP(nextMessageID());
    rsp.setAutoCancel(autoCancel);
    cfind(asuid, cuid, priority, data, tsuid, rsp);
    return rsp;
}

我在我的应用程序中调用,例如

DimseRSP rsp = association.cfind(...

然后我就可以使用

rsp.someMethodOfTheDimseRSPClass()

这可行,但我想打电话

rsp.someMethodOfTheFutureDimseRSPClass()

相反,这应该是可能的,因为 rsp 是实际上从 cfind() 返回的 FutureDimseRSP 实例,但是当然我的 IDE 给我一个错误,因为它认为 rsp 只是一个 DimseRSP

我该怎么办?我可以以某种方式将 DimseRSP 转换为 FutureDimseRSP 以便它可以工作吗?

最佳答案

如果您担心 rsp 可能并不总是 实例 FutureDimseRSP,请使用 instanceof:

if (rsp instanceof FutureDimseRSP) {
    ((FutureDimseRSP)rsp).someMethodOfTheFutureDimseRSPClass();
}
else {
    // handle this...
}

关于Java方法据说返回类的对象但返回子类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49628944/

相关文章:

Java2D/Graphics2D 性能

java - 拥有一个包含指向大多数对象的指针并通过它引用对象的类是一种不好的做法吗?

java - 类转换异常 : BitmapDrawable cannot be cast to LayerDrawable

c++ - C++03 中的函数返回类型推导

java - java中iterator()方法的返回类型

java - 属性初始化Java

java - 如何在 Maven 构建中访问包保护类?

c# - 在 C# 中转换时应该使用 (ObjectType) 还是 'as ObjectType'?

c - Borland C/C++ 将 short 转换为 unsigned int

c++ - 选择正确的模板成员函数的返回类型