'What's the difference between FilterWriter and Writer in Java?

From https://docs.oracle.com/javase/7/docs/api/java/io/Writer.html and https://docs.oracle.com/javase/7/docs/api/java/io/FilterWriter.html, I find that FilterWriter is an abstract class, which extends Writer and has no extra mothods.

I just wonder:

  1. What is the rationale to define FilterWriter as an exact copy of Writer?
  2. What's the difference between FilterWriter and Writer ?


Solution 1:[1]

  1. What is the rationale to define FilterWriter as an exact copy of Writer?

FilterWriter is not an exact copy of Writer. Although declared abstract, it provides implementations of all of Writer's abstract methods, and it overrides some of the concrete methods. These implementations serve FilterWriter's specific purpose, as described in its API docs:

The abstract class FilterWriter itself provides default methods that pass all requests to the contained stream. Subclasses of FilterWriter should override some of these methods and may also provide additional methods and fields.

The class is abstract, despite having no abstract methods, because the functionality described is not directly useful by itself. It is intended to serve as a base class for classes that monitor or modify the character stream as it is written to the underlying Writer.

  1. What's the difference between FilterWriter and Writer?

Functionally, FilterWriter provides concrete implementations for Writer's abstract methods, and it overrides a few others. Type-wise, Writer is a superclass of a bunch of classes that FilterWriter is not a superclass of, including FilterWriter itself.

Solution 2:[2]

The FilterWriter class is the superclass of all of the writer classes that filter output. A subclass of FilterWriter works by wrapping an existing writer, called the underlying writer, and providing additional functionality. The methods of FilterWriter simply override the methods of Writer with versions that call the corresponding methods of the underlying writer.

FilterWriter cannot be instantiated directly; it must be subclassed. An instance of a subclass of FilterWriter is constructed with another Writer object. The methods of a subclass of FilterWriter should override some methods in order to extend their behavior or provide some sort of filtering.

FilterWriter is like FilterOutputStream, except that it deals with a character stream instead of a byte stream.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Bollinger
Solution 2 Buddy