How does Out variable which is defined static and assigned null in System class can access non-static methods of PrintStream class. [duplicate]

杀马特。学长 韩版系。学妹 提交于 2020-12-13 04:20:05

问题


As to access the methods of PrintStram class an object must be created, so how the out variable is able to access those methods when it is assigned null.

  public final static PrintStream out = null;

This is the declaration in System class.

I tried to write the similar code but then it gives NullPointerException. My code is given below.

class First{

public  void display(){
    System.out.println("Hello");
}

}

 class Second{

public final static  First s1=null;

 }

  public class  Third{

  public static void main(String[] args) {

    Second.s1.display();

 }
 }

To make this code run i will have to make either display method static or define s1 as-

public final static  First s1=new First(); 

回答1:


The field isn't null at runtime. It's assigned the relevant stream stdout or something else if it has been redirected. The mechanism is internal to the JVM, so the code isn't readily visible in the JDK sources. You can use System.setOut() to modify the field, which again uses internal mechanisms as the field is final and normally wouldn't be assignable.




回答2:


You may have missed the System.initializeSystemClass() which according to the documentation is called after the class initialization. It initialize the in, out and err stream. It use native methods to do that, so it doesn't have to respect the final modifiers.



来源:https://stackoverflow.com/questions/44261356/how-does-out-variable-which-is-defined-static-and-assigned-null-in-system-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!