简体   繁体   中英

Why we can't call 'println()' method with help of PrintStream class where out is object of this class?

Why we can't call println() method with help of PrintStream class where out is object of this class?

import java.io.*;

class Demo {
    public static void main(String[] args) {
        PrintStream.out.println("Hello");
    }
}

Why we can't call println() method with help of PrintStream class where out is object of this class:

  PrintStream.out.println("Hello"); 

Three reasons:

a) it's not static - you need an instance of the PrintStream class

b) it's got protected visibility - so its not accessibe.

c) the out variable is actually an OutputStream - so it doesn't have a println method.

To use a PrintStream, you want to do something like this:

final PrintStream ps = new PrintStream(new FileOutputStream(new File(filename)));
ps.println("Now is the time for all good men to come to the aid of their party.");
ps.close();

Consult the Javadoc for more information.

Yep what Greg says. Also if you want to print to the console you can just use System.out.println("Manga Bunga");

And if you want to use PrintStream use the println() method after instantiating a PrintStreat object.

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