【发布时间】:2011-09-28 02:05:30
【问题描述】:
在返回类型中使用泛型时,我无法扩展父类 像下面的例子。
如你所知,没有泛型,下面的例子可以正常编译,但它不是类型安全的,因为它的类型应该是 Object。
有什么明确的解决方案(或模式,或建议,任何有用的东西!)我可以参考吗?
class AbstractReader<T>{
public abstract T readNext();
}
class ByteArrayReader extends AbstractReader<byte[]>{
@Override
public byte[] readNext(){ /*...*/ }
}
class StringReader extends ByteArrayReader {
@Override
public String readNext() {
/* The return type is incompatible
with ByteArrayReader.readNext()! */
return new String(bytes);
}
}
【问题讨论】:
标签: java generics subclassing return-type