Why is java.io.OutputStream
not modeled as an interface instead of abstract class?
An interface can prove useful for example unit testing, I thought.
Some of the methods are already implemented. This is not possible for Interfaces.
close()
void flush()
void write(byte[] b)
void write(byte[] b, int off, int len)
Are already implemented with a default implementation.
The javadoc gives a hint:
Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output.
(that is, void write(int b) throws IOException
)
If you look at its actual code, the default other write()
methods of this base abstract class use the sole method you need to implement.
Also, output streams may not be linked to an actual resource (ByteArrayOutputStream
for instance): this class therefore also has default implementations for .close()
and .flush()
which do nothing, and which need to be overriden only by streams having an actual resource behind them.
As for testing purposes, the only difference for unit testing is really that you need to extends
rather than implements
, and not forget to override the methods you need. Or use a mocking library (such as mockito, or jmock, or...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With