user3341953
user3341953

Reputation: 319

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?

Upvotes: 1

Views: 833

Answers (5)

bobbel
bobbel

Reputation: 3356

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);
    }
}

Upvotes: 4

ifloop
ifloop

Reputation: 8386

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

Example:

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

...

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

Upvotes: 1

Tobb
Tobb

Reputation: 12205

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);
}

Upvotes: 2

Mureinik
Mureinik

Reputation: 311163

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);
}

Upvotes: 0

marioc64
marioc64

Reputation: 390

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

Upvotes: 2

Related Questions