First let me apologize for the terrible title, but I had no idea how to summarize this in a single sentence.
public class GenericFun {
public class TypedStream<I extends OutputStream> {
I input;
public I getInput() { return input; }
public void setInput(I input) { this.input = input; }
}
public abstract class GarbageWriter<I extends OutputStream> {
public void writeGarbage(I output) throws Exception {
output.write("Garbage".getBytes());
}
}
public class GarbageWriterExecutor<I extends OutputStream> extends GarbageWriter<I> {
public void writeTrash(TypedStream stream) throws Exception{
this.writeGarbage(stream.getInput()); // Error
this.writeGarbage((I)stream.getInput()); // OK
}
}
}
In the above code (the OutputStream is just an example) in class GarbageWriterExecutor class in the method first line causes compilation error, while the second one don't. I have two questions regarding this.
- Why
stream.getInput()causes error, even thoughTypedStream.Iis known to extendOutputStream? - How can I solve this issue without the ugly casting?