在 System.out.println() 中输出

out in System.out.println()(在 System.out.println() 中输出)

本文介绍了在 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(); 

他让我模拟一个类似的程序,我跟踪它并没有工作,因为 System.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()out 变量设置为适当的值.

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 不能静态设置为该值,因为 System 需要是第一个加载的类之一(在 PrintStream 之前).
  • out 必须是 final,这样它的值就不能被用户直接覆盖.
  • 由于 out 不能静态设置,并且是最终的,我们必须使用 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() 中输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 System.out.println() 中输出

基础教程推荐