各位麻油们,大家学了这么久Java了,确定真的掌握了System.out.println(); 吗?确定了解了Java面向对象编程的含义了吗?今天,我就深层刨析一下这串源代码!

学了这么久的Java,你确定真正知道System.out.println();吗?_调用方法

如果能自己读懂System.out.println(),就真正了解了Java面向对象编程的含义,面向对象编程即创建了对象,所有的事情让对象帮亲力亲为(即对象调用方法)

学了这么久的Java,你确定真正知道System.out.println();吗?_java_02

System.out.println("hello world");
hello world

Process finished with exit code 0

话不多说,首先对System源码进行分析:

System就是java中的一个类

学了这么久的Java,你确定真正知道System.out.println();吗?_源码分析_03

out源码分析:

1.out是System里面的一个静态数据成员,而且这个成员是java.io.PrintStream类的引用

学了这么久的Java,你确定真正知道System.out.println();吗?_调用方法_04

2.out已经存在了并且用static修饰了,所以可以直接使用类名+属性名的方式调用,也就是System.out。

3.out的真实类型是一个静态的PrintStream对象,静态的所以不需要创建对象。

println源码分析:

1.println()就是java.io.PrintStream类里的一个方法,它的作用是向控制台输出信息。

public void println(String x) {
if (getClass() == PrintStream.class) {
writeln(String.valueOf(x));
} else {
synchronized (this) {
print(x);
newLine();
}
}
}

2.之所以可以输出任何东西,是因为里面有方法重载!!

public void println(int x) {
if (getClass() == PrintStream.class) {
writeln(String.valueOf(x));
} else {
synchronized (this) {
print(x);
newLine();
}
}
}
public void println(long x) {
if (getClass() == PrintStream.class) {
writeln(String.valueOf(x));
} else {
synchronized (this) {
print(x);
newLine();
}
}
}
public void println(char[] x) {
if (getClass() == PrintStream.class) {
writeln(x);
} else {
synchronized (this) {
print(x);
newLine();
}
}
}
public void println(String x) {
if (getClass() == PrintStream.class) {
writeln(String.valueOf(x));
} else {
synchronized (this) {
print(x);
newLine();
}
}
}

等等等等。。。。。。。。这里就不一一列举了!!!

总结 System.out.println()就是:类调用对象,对象调用方法!!!

学了这么久的Java,你确定真正知道System.out.println();吗?_源码分析_05

开拓视野:

System.out.print();与System.out.println(); 的区别

public class Text {
public static void main(String[] args) {
System.out.print('a');
System.out.print('b');

System.out.println('c');
System.out.println('d');
}
}

运行结果:

abc
d

System.out.print();输出结果不能换行,System.out.println();输出结果进行换行。

今天的分享就到这里啦!!~感谢大家的观看,希望对大家有帮助的话麻烦给个丝滑三连击。(点赞+转发+关注)
一起加油,一起努力,一起秃见成效!!

学了这么久的Java,你确定真正知道System.out.println();吗?_源码分析_06