javareturnprintstream

Why does PrintStream::printf return a PrintStream?


PrintStream's printf method has a return type of PrintStream and every time it is called it returns this object (the other print methods are void). So why is it designed like this? And for that matter if you have an object of any type that has a method that returns the object itself, what's the point then? You already had the object (this object specifically). So why return this object?


Solution

  • It's called a fluent interface. It's designed so that you can chain together calls like so:

    stream.printf("aaaa")
          .printf("bbbb")
          .printf("cccc");
    

    Rather than doing:

    stream.printf("aaaa");
    stream.printf("bbbb");
    stream.printf("cccc");
    

    It's achieved by returning this at the end of the method:

    class PrintStream extends FilterOutputStream implements Appendable, Closeable {
        //...
    
        public PrintStream printf(String var1, Object... var2) {
            return this.format(var1, var2);
        }
    
        public PrintStream format(String var1, Object... var2) {
            //...
            return this; // <-- here
        }
        //...
    }
    

    As to whether it's a good design pattern in this instance, I'd say not particularly. It's not offensively bad either.