最近在整理IO流的笔记时,发现了这样一个问题······
理解 System.out.println()
在Java.lang包下有一个System类,其中定义了一个类(静态)成员变量:
public final static PrintStream out = null;
由此可见,out只不过是PrintStream的一个对象。由于out在System类中是静态修饰的,所以可以直接通过类名来调用System.out
。(System.in也是一样的道理,这里就不详细说了。)
现在,我们拿到了PrintStream类的一个对象System.out
,通过对象调用方法(println)就更好理解了,所以就得到了这样的语句System.out.println
。
//一般不会有人这样写,只是便于理解。
PrintStream Myout = System.out;
Myout.println("Sivan");
空指针的out
这里out作为对象但是声明为null。但是为什么没有抛出NullPointerException?
因为在System类中有一个静态初始化块:
/* register the natives via the static initializer.
*
* VM will invoke the initializeSystemClass method to complete
* the initialization for this class separated from clinit.
* Note that to use properties set by the VM, see the constraints
* described in the initializeSystemClass method.
*/
private static native void registerNatives();
static {
registerNatives();
}
JVM在加载类时,就是通过registerNatives()
这个静态方法给out赋了初始值,至于具体的操作,可以参考这篇文章:https://zhidao.baidu.com/question/38660871.html。
由此可见,Java中万事万物皆对象。
最重要的来啦~~~
⭐码字不易,求个关注⭐
⭐点个收藏不迷路哦~⭐