javalibrariesjava-iofilter-input

FilterInputStream IS-A InputStream and HAS-A InputStream


I am reading the source code of Java I/O lib and noticed that FilterStream extends the abstract class InputStream favouring inheritance and also has a InputStream as an instance variable favoring composition.Why do we need a IS-A and a HAS-A relationship at the same time with InputStream ?


Solution

  • FilterInputStream "is an" input stream that adds or modifies the behavior of an existing input stream that you need to pass in. For example, its subclass BufferedInputStream adds a buffering capability. Since FilterInputStream needs to hold on to the stream you pass in, there is also a "has a" relationship.

    FilterInputStream is an example of the decorator pattern: https://en.wikipedia.org/wiki/Decorator_pattern