out in System.out.println()

后端 未结 8 1046
刺人心
刺人心 2020-12-01 03:26

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

8条回答
  •  孤城傲影
    2020-12-01 03:57

    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.

    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 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.

提交回复
热议问题