在System.out.println()中输出 [英] out in System.out.println()

查看:133
本文介绍了在System.out.println()中输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先感到遗憾的是,这是一个非常基本的问题,我宣传我仍然是一个代码猴。
我在接受采访时被问及阐明System.out.println();
我解释了以下方式

Firstly regrets if this is a very basic question and i promote that I'm still a code monkey. I was asked in an interview to elucidate System.out.println(); I explained the following way

//this class belongs to java.lang package
class System{
  public static PrintStream out;
}
//this class belongs to java.io package
class PrintStream{
 public void println..
}

我已经解释过System.out是有效的,因为这是我们在java中访问静态变量的方式,而out是PrintStream的一个对象,因此我们可以访问它的方法,总之为

I've explained that System.out is valid since this is the way we access static variables in java, and out is an object of PrintStream and hence we can access its methods, In sum as

System.out.pritnln(); 

他让我模拟一个类似的程序,我跟踪它并没有用,因为系统.out返回null

he asked me to simulate a similar kind of program,i traced and it did not work,since System.out is returning null

我的问题是在java中实例化的对象在哪里?如果我没错,它是预定义的对象吗?什么应该是对此的细致解释。

my question is where is out object instantiated in java ? Is it a predefined object if I'm not wrong. what should be the meticulous explanation for this.

从技术上讲,我们应该叫什么?是一个类型为PrintStream类型的变量,还是应该将其称为PrintStream类型的对象?

Technically what should we call out? Is out a variable of type PrintStream type or should one say it as an object of type PrintStream ?

推荐答案

初始化System.out在实例化类时, null 。这是由 System.java 中的 nullPrintStream()方法设置的,它只返回 null

System.out is initialized to null when the class is instantiated. This is set by the nullPrintStream() method in System.java, which just returns null.

当JVM初始化时,它调用 initializeSystemClass()方法。此方法调用 native 方法 setOut0(),它将设置为变量到适当的值。

When the JVM has initialized, it calls the initializeSystemClass() method. This method calls the native method setOut0() which sets the out variable to the appropriate value.

这可能看起来很奇怪,但由于以下原因,这是必要的操作:

This may seem weird but it is a necessary operation for the following reasons:


  • out 无法静态设置为该值,因为系统需要为1第一个加载的类(在 PrintStream 之前)。

  • out 必须 final ,以便无法直接覆盖其值用户。

  • 由于 out 无法静态设置,并且是最终的,我们必须使用<$覆盖语言的语义c $ c> native 方法, setOut0()

  • out cannot be set statically to the value because System needs to be one of the first loaded classes (before PrintStream).
  • out must be final so that its value cannot be directly overridden by a user.
  • Since out cannot be set statically, and is final, we must override the semantics of the language using a native method, setOut0().

我希望这有助于你理解。

I hope that helps your understanding.

这篇关于在System.out.println()中输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆