Search code examples
javaprintwriter

PrintWriter constructors


I've listed below the 8 constructors of PrintWriter class.
PrintWriter(File file), PrintWriter(File file, String csn), PrintWriter(OutputStream out), PrintWriter(OutputStream out, boolean autoFlush), PrintWriter(String fileName), PrintWriter(String fileName, String csn), PrintWriter(Writer out), PrintWriter(Writer out, boolean autoFlush).

Questions:

  1. If there's no PrintWriter contructor that takes PrintStream, then how come we can write a statment like I've written below?

  2. If there's no PrintWriter contructor that takes BufferedWriter, then how come we can write a statment like I've written below?

          PrintWriter writer1 = new PrintWriter(System.out);
    
          PrintWriter writer2;
          writer2 = new PrintWriter(new BufferedWriter(new FileWriter(new File(outdir, reportFileName))));
    

Thanks in advance.


Solution

  • This is possible because PrintStream inherits from FilterOutputStream and the latter again from OutputStream.

    enter image description here

    A BufferedWriter inherits from Writer.

    enter image description here

    Writer and OutputStream are possible variables in the PrintWriter constructors. The big topic, what we are talking about here, is inheritance. There is a good post for this.