如何在System类中定义为static并指定为null的Out变量可以访问PrintStream类的非静态方法。
问题描述:
对于访问PrintStram类的方法,必须创建一个对象,以便out变量在分配null时如何访问这些方法。如何在System类中定义为static并指定为null的Out变量可以访问PrintStream类的非静态方法。
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();
答
该字段不null
在运行时。它被分配了相关的流stdout
或其他东西,如果它已被重定向。该机制是JVM内部的,因此代码在JDK源代码中不易显示。您可以使用System.setOut()
修改该字段,该字段再次使用内部机制,因为该字段是最终字段,通常不可分配。
答
您可能错过了根据文档在类初始化后调用的System.initializeSystemClass()。它初始化in,out和err流。它使用本地方法来做到这一点,所以它不必尊重最终的修饰符。
它在运行时不'null'。 – Kayaman
本机代码为System.out分配了一个非空值。你的班级没有本地代码。 – VGR