It make sense to see close()
as non-core functionality of stream objects. This is the reason this method is placed in interface Closeable
. One evidence is that class ByteArrayInputStream
does not require the close()
operation.
public abstract class InputStream implements Closeable {}
public abstract class OutputStream implements Closeable, Flushable {}
Based on the above definitions my observation is that interface Closeable
should not be implemented by abstract class InputStream/OutputStream
; it has to be left to concrete sub-classes (like class FileInputStream
) to implement it.
Do you think my understanding is correct?
Best Answer
Just my two cents. The goal of this answer is to give some thoughts and attract more answers, not trying to sound like definitive or even informative.
Why are streams abstract base classes instead of interfaces?
Is the close() method fundamental to the operation of streams?
Contrary to your point of view, I would argue that streams that do not require closing is the minority, rather than majority.
To put it bluntly,
Does the cost-benefit analysis favor the inclusion of the close() method into the stream interface?
It seems so. For streams that do not require explicit closing, it is harmless to require it to provide a trivial
close()
method that does nothing.Similar observation can be found in the C# language, where it is common to see interfaces that subtype from
IDisposable
.Would the failure to include the close() method in the stream interface cause extraordinary harm to implementations that require it?
Yes. Not having it on the interface, or splitting it out to a second
Closeable
interface would cause extraordinary harm.In the first code snippet below, suppose
InputStream
does not contain theclose()
method. Here is what the code would look like:In other words, because the omission implies that "not every InputStream is a Closeable", any consumer of any InputStream instance now has the additional responsibility to check whether the instance is indeed Closeable.
The
try-with
pattern would then also require more code, because you cannot use an InputStream there unless you can cast it into a Closeable.Is it a violation of Interface Segregation Principle?
No.
Specifically, Interface Segregation Principle does not require: