首先让我为可怕的头衔道歉,但我不知道如何用一句话来总结这一点.
public class GenericFun {
public class TypedStream {
I input;
public I getInput() { return input; }
public void setInput(I input) { this.input = input; }
}
public abstract class GarbageWriter {
public void writeGarbage(I output) throws Exception {
output.write("Garbage".getBytes());
}
}
public class GarbageWriterExecutor extends GarbageWriter {
public void writeTrash(TypedStream stream) throws Exception{
this.writeGarbage(stream.getInput()); // Error
this.writeGarbage((I)stream.getInput()); // OK
}
}
}
在上面的代码(OutputStream只是一个例子)中,类GarbageWriterExecutor类在方法第一行导致编译错误,而第二行则没有.我有两个问题.
>为什么stream.getInput()会导致错误,即使已知TypedStream.I扩展OutputStream?
>如果没有丑陋的演员,我怎么能解决这个问题呢?
解决方法:
TypedStream流将禁用泛型类型检查,因此编译器只知道getInput()将返回一个对象,因此错误.
请尝试使用writeTrash(TypedStream< I> stream).
也许你的事件想要使用writeTrash(TypedStream stream),以便能够传递为I或I的子类参数化的任何TypedStream.
还有另一种选择
public class GarbageWriterExecutor extends GarbageWriter {
public void writeTrash(TypedStream> stream) throws Exception{
this.writeGarbage(stream.getInput());
}
}
要么
public class GarbageWriterExecutor extends GarbageWriter {
public void writeTrash(TypedStream extends OutputStream> stream) throws Exception{
this.writeGarbage(stream.getInput());
}
}
标签:java,inheritance,generics
来源: https://codeday.me/bug/20190725/1532924.html