如何在System类中定义为static且赋值为null的Out变量可以访问PrintStream类的非静态方法。

时间:2017-05-30 11:44:58

标签: java static system.out printstream

至于访问PrintStram类的方法,必须创建一个对象,因此当out变量被赋值为null时,out变量如何能够访问这些方法。

  public final static PrintStream out = null;

这是System类中的声明。

我试着编写类似的代码但是它给出了NullPointerException。我的代码如下。

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();

 }
 }

要使此代码运行,我必须使显示方法为静态或将s1定义为 -

public final static  First s1=new First(); 

2 个答案:

答案 0 :(得分:0)

该字段在运行时不是null。如果已重定向,则会为相关流stdout或其他内容分配。该机制是JVM的内部机制,因此代码在JDK源中不易看到。您可以使用System.setOut()修改字段,该字段再次使用内部机制,因为字段是最终字段,通常不可分配。

答案 1 :(得分:0)

您可能错过了System.initializeSystemClass(),根据在类初始化之后调用的文档。它初始化in,out和err流。它使用原生方法来做到这一点,所以它不必尊重最终修饰符。