The Appendable interface

To illustrate Java interfaces, we'll look at an example from the JDK. Let's suppose we write a method to append some data to a StringBuffer:

public void appendData(StringBuffer sb) {

Now, this is great if we have a StringBuffer to pass in. But supposing we want a version to output the data to a Writer instead of a StringBuffer. Of course, if Writer were a subclass of StringBuffer, the above method would just work. But sadly, it isn't. So we could just write another version:

public void appendData(Writer wr) {

We'd have the same problem if we wanted to write the data to an OutputStream, StringBuilder, or various other plausible objects that we might want to append the data to. If this were part of some library that we wanted to make as flexible as possible, we could end up with goodness knows how many versions of the method, each taking a different type of object and calling a different method as appropriate to that object1.

As we'll see on the next page, this is where the Appendable interface steps in.

1. You may be reminded of the two versions of Throwable.printStackTrace(), which of course date back to the days before Appendable.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.