要访问PrintStram类的方法,必须创建一个对象,那么当out变量被分配为null时,它如何能够访问这些方法。
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() 修改该字段,该字段再次使用内部机制,因为该字段是最终字段,通常不可分配。
关于java - System 类中定义为静态并分配 null 的 Out 变量如何访问 PrintStream 类的非静态方法。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44261356/