简体   繁体   中英

How to use System.out as an argument in method in java

I have a method in java display,

when i used C++, it seems that I could display(ListNode L, OutputStream out) but, could I then out System.out in it? it seems out.write is ok not out.println?

What should I do if I want to use System.out as parameter?

Since the member System.out is of class PrintStream you could do:

void display(PrintStream out) {
    out.println("42!");
}

For better visualization of the hierarchy:

Object
  |---OutputStream
  |     |---FileOutputStream
  |     |---FilterOutputStream
  |           |---PrintStream (System.out)
  |
  |---InputStream (System.in)
  |     |---FileInputStream

To solve the real problem, think about having an interface with two classes which implements it.

For example (without exception handling):

interface Display {
    void display(String message);
}

class ConsoleDisplay implements Display {
    void display(String message) {
        System.out.println(message);
    }
}

class FileDisplay implements Display {
    FileOutputStream out;

    FileDisplay(String filename) {
        out = new FileOutputStream(filename);
    }

    void display(String message) {
        out.write(message.getBytes());
    }
}

class DoingStuff {
    public static void main(String[] args) {
        Display dispFile = new FileDisplay("logfile.log");
        display("42!", dispFile);

        Display dispConsole = new ConsoleDisplay();
        display("42!", dispConsole);
    }

    static void display(String message, Display disp) {
        disp.display(message);
    }
}

Why would you want to pass System.out as a parameter, when it is available everywhere?

Why not just do this:

public void display(final String toDisplay) {
    System.out.println(toDisplay);
}

Type of System.out is PrintStream. Here is the javadoc.

In Java 8 one might think of method references as well.

Example:

private List<ListNode> nodes = new LinkedList<>();

...

nodes.forEarch(System.out :: println);

System.out is a PrintStream instance. System.out.println is a method invocation on that instance. So, you could do the following:

public display (ListNode l, PrintStream out) {
    out.println("L is " + l);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM