为什么我们不能在PrintStream类的帮助下调用'println()'方法,其中out是这个类的对象?

Jav*_*nal 2 java println

为什么我们不能println()在PrintStream类的帮助下调用方法,其中out是这个类的对象?

import java.io.*;

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

Gre*_*pff 7

为什么我们不能在这个类的对象的类的println()帮助下调用方法:PrintStreamout

 PrintStream.out.println("Hello");
Run Code Online (Sandbox Code Playgroud)

三个原因:

a)它不是静态的 - 你需要一个PrintStream类的实例

b)它具有protected可见性 - 所以它不是accessibe.

c)out变量实际上是OutputStream- 所以它没有println方法.

要使用PrintStream,您需要执行以下操作:

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();
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请咨询Javadoc.