Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutputStream as interface

Tags:

java

io

interface

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.

like image 339
sgp15 Avatar asked Jan 10 '13 16:01

sgp15


2 Answers

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.

like image 135
MrSmith42 Avatar answered Oct 13 '22 16:10

MrSmith42


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...).

like image 31
fge Avatar answered Oct 13 '22 16:10

fge