During researches within Android's Developer Database, I stumbled upon PrintWriterPrinter (inside android.util): https://developer.android.com/reference/android/util/PrintWriterPrinter.html
The source code of the PrintWriterPrinter class is shown below:
package android.util;
import java.io.PrintWriter;
/**
* Implementation of a {@link android.util.Printer} that sends its output
* to a {@link java.io.PrintWriter}.
*/
public class PrintWriterPrinter implements Printer {
private final PrintWriter mPW;
/**
* Create a new Printer that sends to a PrintWriter object.
*
* @param pw The PrintWriter where you would like output to go.
*/
public PrintWriterPrinter(PrintWriter pw) {
mPW = pw;
}
public void println(String x) {
mPW.println(x);
}
}
As you can see, it only has one single method: println(String x) which essentially applies println to the passed PrintWriter. My question: Why would I use this useless PrintWriterPrinter if I could just manually call println on my PrintWriter object instead of creating a PrintWriterPrinter and then call println on that (which then calls println on a PrintWriter)?
The key is implements Printer
.
When you learned Java programming, you learned about Java interfaces . A class declares that it implements an interface via the implements
keyword; PrintWriterPrinter implements Printer
indicates that PrintWriterPrinter
implements the Printer
interface.
If you look at the Printer
interface in the JavaDocs, you will see that it defines that sole println()
method. However, if you look carefully, you will see that the JavaDocs list four implementations of that interface: LogPrinter
, PrintStreamPrinter
, PrintWriterPrinter
, and StringBuilderPrinter
.
Through what is known as polymorphism , other code can work with an object known to implement the Printer
interface — calling println()
on that object — without knowing or caring which of these four implementations lies behind that object. Other developers could create yet other implementations of the Printer
interface (eg, one that stores the last 50 lines in an ArrayList
), and the rest of the framework needing a Printer
could use that custom implementation without issue.
是否可以在PrintWriter上隐藏某些特定用途的方法,例如冲洗/关闭方法?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.