为什么 java 使用 System.out.print/println 而不是 print 或 println?

Why does java use System.out.print/println instead of just print or println?

这个 post 可能被认为不适合 Whosebug,尽管我并不是想侮辱 Java 语言或类似的东西。我喜欢在 Java 中编码,但是关于 System.out.println 的一些事情我一直想知道。

为什么我们每次要打印时总是被迫输入System.out.println() 或System.out.print()?当然,我们可以在程序中创建一个 void 函数来节省时间和精力,我们将有几个打印语句(我有时会这样做),如下所示:

public static void print(String output) {
    System.out.print(output);
}

然后只调用 print(如果你想真正彻底,你可以用涉及 ints、doubles、chars 等的参数重载函数)。但是,为什么 Java 语言本身还不允许我们仅通过编写 print 来打印到控制台?某些语言(例如 Python)使控制台打印变得简洁明了 - 那么为什么 Java 不呢?

再说一次 - 我并不是说 Java 语言设计不佳,或者试图启动一个旨在 bash Java 的线程。我确信语言设计者按照他们的方式设计它有他们的理由,这将帮助我理解为什么会这样。只需要键入 print 而不是 System.out.print 会容易得多,因此我们必须键入 System.out.print 一定有原因 - 我只是无法弄清楚这些原因。我已尝试使用谷歌搜索有关此问题的信息,但找不到与此问题相关的任何内容。

请避免对 Java 语言做出自以为是的回应 - 我想要解释这种现象的真实事实。

简单地说,Java 没有全局函数。

此外,根据 The Java Language Environment(James Gosling 合着的 90 年代书籍):

Java has no functions. Object-oriented programming supersedes functional and procedural styles. Mixing the two styles just leads to confusion and dilutes the purity of an object-oriented language. Anything you can do with a function you can do just as well by defining a class and creating methods for that class.

It's not to say that functions and procedures are inherently wrong. But given classes and methods, we're now down to only one way to express a given task. By eliminating functions, your job as a programmer is immensely simplified: you work only with classes and their methods.

所以至少有一种语言设计者的推理。


您可以通过静态导入来缩短调用 System.out:

import static System.out;

class Example {
    public static void main(String[] args) {
        out.println("hello world!");
    }
}

由于System.out是一个对象,它的实例方法不能被静态导入。